Send failure event if we fail to handle a HTLC
[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::{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::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
27 use routing::gossip::NetworkGraph;
28 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
29 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
30 use ln::msgs;
31 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, OptionalField, 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::{Transaction, TxIn, 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 sync::{Arc, Mutex};
59
60 use ln::functional_test_utils::*;
61 use ln::chan_utils::CommitmentTransaction;
62
63 #[test]
64 fn test_insane_channel_opens() {
65         // Stand up a network of 2 nodes
66         use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
67         let mut cfg = UserConfig::default();
68         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
69         let chanmon_cfgs = create_chanmon_cfgs(2);
70         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
71         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
72         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
73
74         // Instantiate channel parameters where we push the maximum msats given our
75         // funding satoshis
76         let channel_value_sat = 31337; // same as funding satoshis
77         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
78         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
79
80         // Have node0 initiate a channel to node1 with aforementioned parameters
81         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
82
83         // Extract the channel open message from node0 to node1
84         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
85
86         // Test helper that asserts we get the correct error string given a mutator
87         // that supposedly makes the channel open message insane
88         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
89                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
90                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
91                 assert_eq!(msg_events.len(), 1);
92                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
93                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
94                         match action {
95                                 &ErrorAction::SendErrorMessage { .. } => {
96                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
97                                 },
98                                 _ => panic!("unexpected event!"),
99                         }
100                 } else { assert!(false); }
101         };
102
103         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
104
105         // Test all mutations that would make the channel open message insane
106         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 });
107         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 });
108
109         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
110
111         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 });
112
113         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
114
115         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 });
116
117         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 });
118
119         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
120
121         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
122 }
123
124 #[test]
125 fn test_funding_exceeds_no_wumbo_limit() {
126         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
127         // them.
128         use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
129         let chanmon_cfgs = create_chanmon_cfgs(2);
130         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
131         node_cfgs[1].features = InitFeatures::known().clear_wumbo();
132         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
133         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
134
135         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
136                 Err(APIError::APIMisuseError { err }) => {
137                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
138                 },
139                 _ => panic!()
140         }
141 }
142
143 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
144         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
145         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
146         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
147         // in normal testing, we test it explicitly here.
148         let chanmon_cfgs = create_chanmon_cfgs(2);
149         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
150         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
151         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
152
153         // Have node0 initiate a channel to node1 with aforementioned parameters
154         let mut push_amt = 100_000_000;
155         let feerate_per_kw = 253;
156         let opt_anchors = false;
157         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
158         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
159
160         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();
161         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
162         if !send_from_initiator {
163                 open_channel_message.channel_reserve_satoshis = 0;
164                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
165         }
166         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
167
168         // Extract the channel accept message from node1 to node0
169         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
170         if send_from_initiator {
171                 accept_channel_message.channel_reserve_satoshis = 0;
172                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
173         }
174         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
175         {
176                 let mut lock;
177                 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
178                 chan.holder_selected_channel_reserve_satoshis = 0;
179                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
180         }
181
182         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
183         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
184         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
185
186         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
187         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
188         if send_from_initiator {
189                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
190                         // Note that for outbound channels we have to consider the commitment tx fee and the
191                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
192                         // well as an additional HTLC.
193                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
194         } else {
195                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
196         }
197 }
198
199 #[test]
200 fn test_counterparty_no_reserve() {
201         do_test_counterparty_no_reserve(true);
202         do_test_counterparty_no_reserve(false);
203 }
204
205 #[test]
206 fn test_async_inbound_update_fee() {
207         let chanmon_cfgs = create_chanmon_cfgs(2);
208         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
209         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
210         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
211         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
212
213         // balancing
214         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
215
216         // A                                        B
217         // update_fee                            ->
218         // send (1) commitment_signed            -.
219         //                                       <- update_add_htlc/commitment_signed
220         // send (2) RAA (awaiting remote revoke) -.
221         // (1) commitment_signed is delivered    ->
222         //                                       .- send (3) RAA (awaiting remote revoke)
223         // (2) RAA is delivered                  ->
224         //                                       .- send (4) commitment_signed
225         //                                       <- (3) RAA is delivered
226         // send (5) commitment_signed            -.
227         //                                       <- (4) commitment_signed is delivered
228         // send (6) RAA                          -.
229         // (5) commitment_signed is delivered    ->
230         //                                       <- RAA
231         // (6) RAA is delivered                  ->
232
233         // First nodes[0] generates an update_fee
234         {
235                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
236                 *feerate_lock += 20;
237         }
238         nodes[0].node.timer_tick_occurred();
239         check_added_monitors!(nodes[0], 1);
240
241         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
242         assert_eq!(events_0.len(), 1);
243         let (update_msg, commitment_signed) = match events_0[0] { // (1)
244                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
245                         (update_fee.as_ref(), commitment_signed)
246                 },
247                 _ => panic!("Unexpected event"),
248         };
249
250         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
251
252         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
253         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
254         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
255         check_added_monitors!(nodes[1], 1);
256
257         let payment_event = {
258                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
259                 assert_eq!(events_1.len(), 1);
260                 SendEvent::from_event(events_1.remove(0))
261         };
262         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
263         assert_eq!(payment_event.msgs.len(), 1);
264
265         // ...now when the messages get delivered everyone should be happy
266         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
267         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
268         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
269         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
270         check_added_monitors!(nodes[0], 1);
271
272         // deliver(1), generate (3):
273         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
274         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
275         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
276         check_added_monitors!(nodes[1], 1);
277
278         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
279         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
280         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
281         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
282         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
283         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
284         assert!(bs_update.update_fee.is_none()); // (4)
285         check_added_monitors!(nodes[1], 1);
286
287         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
288         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
289         assert!(as_update.update_add_htlcs.is_empty()); // (5)
290         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
291         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
292         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
293         assert!(as_update.update_fee.is_none()); // (5)
294         check_added_monitors!(nodes[0], 1);
295
296         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
297         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
298         // only (6) so get_event_msg's assert(len == 1) passes
299         check_added_monitors!(nodes[0], 1);
300
301         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
302         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
303         check_added_monitors!(nodes[1], 1);
304
305         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
306         check_added_monitors!(nodes[0], 1);
307
308         let events_2 = nodes[0].node.get_and_clear_pending_events();
309         assert_eq!(events_2.len(), 1);
310         match events_2[0] {
311                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
312                 _ => panic!("Unexpected event"),
313         }
314
315         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
316         check_added_monitors!(nodes[1], 1);
317 }
318
319 #[test]
320 fn test_update_fee_unordered_raa() {
321         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
322         // crash in an earlier version of the update_fee patch)
323         let chanmon_cfgs = create_chanmon_cfgs(2);
324         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
325         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
326         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
327         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
328
329         // balancing
330         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
331
332         // First nodes[0] generates an update_fee
333         {
334                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
335                 *feerate_lock += 20;
336         }
337         nodes[0].node.timer_tick_occurred();
338         check_added_monitors!(nodes[0], 1);
339
340         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
341         assert_eq!(events_0.len(), 1);
342         let update_msg = match events_0[0] { // (1)
343                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
344                         update_fee.as_ref()
345                 },
346                 _ => panic!("Unexpected event"),
347         };
348
349         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
350
351         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
352         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
353         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
354         check_added_monitors!(nodes[1], 1);
355
356         let payment_event = {
357                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
358                 assert_eq!(events_1.len(), 1);
359                 SendEvent::from_event(events_1.remove(0))
360         };
361         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
362         assert_eq!(payment_event.msgs.len(), 1);
363
364         // ...now when the messages get delivered everyone should be happy
365         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
366         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
367         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
368         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
369         check_added_monitors!(nodes[0], 1);
370
371         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
372         check_added_monitors!(nodes[1], 1);
373
374         // We can't continue, sadly, because our (1) now has a bogus signature
375 }
376
377 #[test]
378 fn test_multi_flight_update_fee() {
379         let chanmon_cfgs = create_chanmon_cfgs(2);
380         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
381         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
382         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
383         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
384
385         // A                                        B
386         // update_fee/commitment_signed          ->
387         //                                       .- send (1) RAA and (2) commitment_signed
388         // update_fee (never committed)          ->
389         // (3) update_fee                        ->
390         // We have to manually generate the above update_fee, it is allowed by the protocol but we
391         // don't track which updates correspond to which revoke_and_ack responses so we're in
392         // AwaitingRAA mode and will not generate the update_fee yet.
393         //                                       <- (1) RAA delivered
394         // (3) is generated and send (4) CS      -.
395         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
396         // know the per_commitment_point to use for it.
397         //                                       <- (2) commitment_signed delivered
398         // revoke_and_ack                        ->
399         //                                          B should send no response here
400         // (4) commitment_signed delivered       ->
401         //                                       <- RAA/commitment_signed delivered
402         // revoke_and_ack                        ->
403
404         // First nodes[0] generates an update_fee
405         let initial_feerate;
406         {
407                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
408                 initial_feerate = *feerate_lock;
409                 *feerate_lock = initial_feerate + 20;
410         }
411         nodes[0].node.timer_tick_occurred();
412         check_added_monitors!(nodes[0], 1);
413
414         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
415         assert_eq!(events_0.len(), 1);
416         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
417                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
418                         (update_fee.as_ref().unwrap(), commitment_signed)
419                 },
420                 _ => panic!("Unexpected event"),
421         };
422
423         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
424         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
425         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
426         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
427         check_added_monitors!(nodes[1], 1);
428
429         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
430         // transaction:
431         {
432                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
433                 *feerate_lock = initial_feerate + 40;
434         }
435         nodes[0].node.timer_tick_occurred();
436         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
437         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
438
439         // Create the (3) update_fee message that nodes[0] will generate before it does...
440         let mut update_msg_2 = msgs::UpdateFee {
441                 channel_id: update_msg_1.channel_id.clone(),
442                 feerate_per_kw: (initial_feerate + 30) as u32,
443         };
444
445         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
446
447         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
448         // Deliver (3)
449         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
450
451         // Deliver (1), generating (3) and (4)
452         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
453         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
454         check_added_monitors!(nodes[0], 1);
455         assert!(as_second_update.update_add_htlcs.is_empty());
456         assert!(as_second_update.update_fulfill_htlcs.is_empty());
457         assert!(as_second_update.update_fail_htlcs.is_empty());
458         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
459         // Check that the update_fee newly generated matches what we delivered:
460         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
461         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
462
463         // Deliver (2) commitment_signed
464         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
465         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
466         check_added_monitors!(nodes[0], 1);
467         // No commitment_signed so get_event_msg's assert(len == 1) passes
468
469         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
470         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
471         check_added_monitors!(nodes[1], 1);
472
473         // Delever (4)
474         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
475         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
476         check_added_monitors!(nodes[1], 1);
477
478         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
479         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
480         check_added_monitors!(nodes[0], 1);
481
482         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
483         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
484         // No commitment_signed so get_event_msg's assert(len == 1) passes
485         check_added_monitors!(nodes[0], 1);
486
487         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
488         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
489         check_added_monitors!(nodes[1], 1);
490 }
491
492 fn do_test_sanity_on_in_flight_opens(steps: u8) {
493         // Previously, we had issues deserializing channels when we hadn't connected the first block
494         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
495         // serialization round-trips and simply do steps towards opening a channel and then drop the
496         // Node objects.
497
498         let chanmon_cfgs = create_chanmon_cfgs(2);
499         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
500         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
501         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
502
503         if steps & 0b1000_0000 != 0{
504                 let block = Block {
505                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
506                         txdata: vec![],
507                 };
508                 connect_block(&nodes[0], &block);
509                 connect_block(&nodes[1], &block);
510         }
511
512         if steps & 0x0f == 0 { return; }
513         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
514         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
515
516         if steps & 0x0f == 1 { return; }
517         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
518         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
519
520         if steps & 0x0f == 2 { return; }
521         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
522
523         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
524
525         if steps & 0x0f == 3 { return; }
526         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
527         check_added_monitors!(nodes[0], 0);
528         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
529
530         if steps & 0x0f == 4 { return; }
531         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
532         {
533                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
534                 assert_eq!(added_monitors.len(), 1);
535                 assert_eq!(added_monitors[0].0, funding_output);
536                 added_monitors.clear();
537         }
538         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
539
540         if steps & 0x0f == 5 { return; }
541         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
542         {
543                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
544                 assert_eq!(added_monitors.len(), 1);
545                 assert_eq!(added_monitors[0].0, funding_output);
546                 added_monitors.clear();
547         }
548
549         let events_4 = nodes[0].node.get_and_clear_pending_events();
550         assert_eq!(events_4.len(), 0);
551
552         if steps & 0x0f == 6 { return; }
553         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
554
555         if steps & 0x0f == 7 { return; }
556         confirm_transaction_at(&nodes[0], &tx, 2);
557         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
558         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
559 }
560
561 #[test]
562 fn test_sanity_on_in_flight_opens() {
563         do_test_sanity_on_in_flight_opens(0);
564         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
565         do_test_sanity_on_in_flight_opens(1);
566         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
567         do_test_sanity_on_in_flight_opens(2);
568         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
569         do_test_sanity_on_in_flight_opens(3);
570         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
571         do_test_sanity_on_in_flight_opens(4);
572         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
573         do_test_sanity_on_in_flight_opens(5);
574         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
575         do_test_sanity_on_in_flight_opens(6);
576         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
577         do_test_sanity_on_in_flight_opens(7);
578         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
579         do_test_sanity_on_in_flight_opens(8);
580         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
581 }
582
583 #[test]
584 fn test_update_fee_vanilla() {
585         let chanmon_cfgs = create_chanmon_cfgs(2);
586         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
587         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
588         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
589         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
590
591         {
592                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
593                 *feerate_lock += 25;
594         }
595         nodes[0].node.timer_tick_occurred();
596         check_added_monitors!(nodes[0], 1);
597
598         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
599         assert_eq!(events_0.len(), 1);
600         let (update_msg, commitment_signed) = match events_0[0] {
601                         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 } } => {
602                         (update_fee.as_ref(), commitment_signed)
603                 },
604                 _ => panic!("Unexpected event"),
605         };
606         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
607
608         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
609         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
610         check_added_monitors!(nodes[1], 1);
611
612         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
613         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
614         check_added_monitors!(nodes[0], 1);
615
616         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
617         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
618         // No commitment_signed so get_event_msg's assert(len == 1) passes
619         check_added_monitors!(nodes[0], 1);
620
621         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
622         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
623         check_added_monitors!(nodes[1], 1);
624 }
625
626 #[test]
627 fn test_update_fee_that_funder_cannot_afford() {
628         let chanmon_cfgs = create_chanmon_cfgs(2);
629         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
630         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
631         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
632         let channel_value = 5000;
633         let push_sats = 700;
634         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
635         let channel_id = chan.2;
636         let secp_ctx = Secp256k1::new();
637         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
638
639         let opt_anchors = false;
640
641         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
642         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
643         // calculate two different feerates here - the expected local limit as well as the expected
644         // remote limit.
645         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;
646         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
647         {
648                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
649                 *feerate_lock = feerate;
650         }
651         nodes[0].node.timer_tick_occurred();
652         check_added_monitors!(nodes[0], 1);
653         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
654
655         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
656
657         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
658
659         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
660         {
661                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
662
663                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
664                 assert_eq!(commitment_tx.output.len(), 2);
665                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
666                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
667                 actual_fee = channel_value - actual_fee;
668                 assert_eq!(total_fee, actual_fee);
669         }
670
671         {
672                 // Increment the feerate by a small constant, accounting for rounding errors
673                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
674                 *feerate_lock += 4;
675         }
676         nodes[0].node.timer_tick_occurred();
677         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
678         check_added_monitors!(nodes[0], 0);
679
680         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
681
682         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
683         // needed to sign the new commitment tx and (2) sign the new commitment tx.
684         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
685                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
686                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
687                 let chan_signer = local_chan.get_signer();
688                 let pubkeys = chan_signer.pubkeys();
689                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
690                  pubkeys.funding_pubkey)
691         };
692         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
693                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
694                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
695                 let chan_signer = remote_chan.get_signer();
696                 let pubkeys = chan_signer.pubkeys();
697                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
698                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
699                  pubkeys.funding_pubkey)
700         };
701
702         // Assemble the set of keys we can use for signatures for our commitment_signed message.
703         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
704                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
705
706         let res = {
707                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
708                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
709                 let local_chan_signer = local_chan.get_signer();
710                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
711                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
712                         INITIAL_COMMITMENT_NUMBER - 1,
713                         push_sats,
714                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
715                         opt_anchors, local_funding, remote_funding,
716                         commit_tx_keys.clone(),
717                         non_buffer_feerate + 4,
718                         &mut htlcs,
719                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
720                 );
721                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
722         };
723
724         let commit_signed_msg = msgs::CommitmentSigned {
725                 channel_id: chan.2,
726                 signature: res.0,
727                 htlc_signatures: res.1
728         };
729
730         let update_fee = msgs::UpdateFee {
731                 channel_id: chan.2,
732                 feerate_per_kw: non_buffer_feerate + 4,
733         };
734
735         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
736
737         //While producing the commitment_signed response after handling a received update_fee request the
738         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
739         //Should produce and error.
740         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
741         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
742         check_added_monitors!(nodes[1], 1);
743         check_closed_broadcast!(nodes[1], true);
744         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
745 }
746
747 #[test]
748 fn test_update_fee_with_fundee_update_add_htlc() {
749         let chanmon_cfgs = create_chanmon_cfgs(2);
750         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
751         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
752         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
753         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
754
755         // balancing
756         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
757
758         {
759                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
760                 *feerate_lock += 20;
761         }
762         nodes[0].node.timer_tick_occurred();
763         check_added_monitors!(nodes[0], 1);
764
765         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
766         assert_eq!(events_0.len(), 1);
767         let (update_msg, commitment_signed) = match events_0[0] {
768                         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 } } => {
769                         (update_fee.as_ref(), commitment_signed)
770                 },
771                 _ => panic!("Unexpected event"),
772         };
773         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
774         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
775         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
776         check_added_monitors!(nodes[1], 1);
777
778         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
779
780         // nothing happens since node[1] is in AwaitingRemoteRevoke
781         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
782         {
783                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
784                 assert_eq!(added_monitors.len(), 0);
785                 added_monitors.clear();
786         }
787         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
788         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
789         // node[1] has nothing to do
790
791         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
792         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
793         check_added_monitors!(nodes[0], 1);
794
795         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
796         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
797         // No commitment_signed so get_event_msg's assert(len == 1) passes
798         check_added_monitors!(nodes[0], 1);
799         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
800         check_added_monitors!(nodes[1], 1);
801         // AwaitingRemoteRevoke ends here
802
803         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
804         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
805         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
806         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
807         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
808         assert_eq!(commitment_update.update_fee.is_none(), true);
809
810         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
811         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
812         check_added_monitors!(nodes[0], 1);
813         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
814
815         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
816         check_added_monitors!(nodes[1], 1);
817         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
818
819         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
820         check_added_monitors!(nodes[1], 1);
821         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
822         // No commitment_signed so get_event_msg's assert(len == 1) passes
823
824         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
825         check_added_monitors!(nodes[0], 1);
826         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
827
828         expect_pending_htlcs_forwardable!(nodes[0]);
829
830         let events = nodes[0].node.get_and_clear_pending_events();
831         assert_eq!(events.len(), 1);
832         match events[0] {
833                 Event::PaymentReceived { .. } => { },
834                 _ => panic!("Unexpected event"),
835         };
836
837         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
838
839         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
840         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
841         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
842         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
843         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
844 }
845
846 #[test]
847 fn test_update_fee() {
848         let chanmon_cfgs = create_chanmon_cfgs(2);
849         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
850         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
851         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
852         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
853         let channel_id = chan.2;
854
855         // A                                        B
856         // (1) update_fee/commitment_signed      ->
857         //                                       <- (2) revoke_and_ack
858         //                                       .- send (3) commitment_signed
859         // (4) update_fee/commitment_signed      ->
860         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
861         //                                       <- (3) commitment_signed delivered
862         // send (6) revoke_and_ack               -.
863         //                                       <- (5) deliver revoke_and_ack
864         // (6) deliver revoke_and_ack            ->
865         //                                       .- send (7) commitment_signed in response to (4)
866         //                                       <- (7) deliver commitment_signed
867         // revoke_and_ack                        ->
868
869         // Create and deliver (1)...
870         let feerate;
871         {
872                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
873                 feerate = *feerate_lock;
874                 *feerate_lock = feerate + 20;
875         }
876         nodes[0].node.timer_tick_occurred();
877         check_added_monitors!(nodes[0], 1);
878
879         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
880         assert_eq!(events_0.len(), 1);
881         let (update_msg, commitment_signed) = match events_0[0] {
882                         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 } } => {
883                         (update_fee.as_ref(), commitment_signed)
884                 },
885                 _ => panic!("Unexpected event"),
886         };
887         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
888
889         // Generate (2) and (3):
890         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
891         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
892         check_added_monitors!(nodes[1], 1);
893
894         // Deliver (2):
895         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
896         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
897         check_added_monitors!(nodes[0], 1);
898
899         // Create and deliver (4)...
900         {
901                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
902                 *feerate_lock = feerate + 30;
903         }
904         nodes[0].node.timer_tick_occurred();
905         check_added_monitors!(nodes[0], 1);
906         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
907         assert_eq!(events_0.len(), 1);
908         let (update_msg, commitment_signed) = match events_0[0] {
909                         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 } } => {
910                         (update_fee.as_ref(), commitment_signed)
911                 },
912                 _ => panic!("Unexpected event"),
913         };
914
915         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
916         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
917         check_added_monitors!(nodes[1], 1);
918         // ... creating (5)
919         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
920         // No commitment_signed so get_event_msg's assert(len == 1) passes
921
922         // Handle (3), creating (6):
923         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
924         check_added_monitors!(nodes[0], 1);
925         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
926         // No commitment_signed so get_event_msg's assert(len == 1) passes
927
928         // Deliver (5):
929         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
930         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
931         check_added_monitors!(nodes[0], 1);
932
933         // Deliver (6), creating (7):
934         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
935         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
936         assert!(commitment_update.update_add_htlcs.is_empty());
937         assert!(commitment_update.update_fulfill_htlcs.is_empty());
938         assert!(commitment_update.update_fail_htlcs.is_empty());
939         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
940         assert!(commitment_update.update_fee.is_none());
941         check_added_monitors!(nodes[1], 1);
942
943         // Deliver (7)
944         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
945         check_added_monitors!(nodes[0], 1);
946         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
947         // No commitment_signed so get_event_msg's assert(len == 1) passes
948
949         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
950         check_added_monitors!(nodes[1], 1);
951         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
952
953         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
954         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
955         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
956         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
957         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
958 }
959
960 #[test]
961 fn fake_network_test() {
962         // Simple test which builds a network of ChannelManagers, connects them to each other, and
963         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
964         let chanmon_cfgs = create_chanmon_cfgs(4);
965         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
966         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
967         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
968
969         // Create some initial channels
970         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
971         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
972         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
973
974         // Rebalance the network a bit by relaying one payment through all the channels...
975         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
976         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
977         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
978         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
979
980         // Send some more payments
981         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
982         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
983         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
984
985         // Test failure packets
986         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
987         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
988
989         // Add a new channel that skips 3
990         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
991
992         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
993         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
994         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
995         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
996         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
997         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
998         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
999
1000         // Do some rebalance loop payments, simultaneously
1001         let mut hops = Vec::with_capacity(3);
1002         hops.push(RouteHop {
1003                 pubkey: nodes[2].node.get_our_node_id(),
1004                 node_features: NodeFeatures::empty(),
1005                 short_channel_id: chan_2.0.contents.short_channel_id,
1006                 channel_features: ChannelFeatures::empty(),
1007                 fee_msat: 0,
1008                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1009         });
1010         hops.push(RouteHop {
1011                 pubkey: nodes[3].node.get_our_node_id(),
1012                 node_features: NodeFeatures::empty(),
1013                 short_channel_id: chan_3.0.contents.short_channel_id,
1014                 channel_features: ChannelFeatures::empty(),
1015                 fee_msat: 0,
1016                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1017         });
1018         hops.push(RouteHop {
1019                 pubkey: nodes[1].node.get_our_node_id(),
1020                 node_features: NodeFeatures::known(),
1021                 short_channel_id: chan_4.0.contents.short_channel_id,
1022                 channel_features: ChannelFeatures::known(),
1023                 fee_msat: 1000000,
1024                 cltv_expiry_delta: TEST_FINAL_CLTV,
1025         });
1026         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;
1027         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;
1028         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;
1029
1030         let mut hops = Vec::with_capacity(3);
1031         hops.push(RouteHop {
1032                 pubkey: nodes[3].node.get_our_node_id(),
1033                 node_features: NodeFeatures::empty(),
1034                 short_channel_id: chan_4.0.contents.short_channel_id,
1035                 channel_features: ChannelFeatures::empty(),
1036                 fee_msat: 0,
1037                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1038         });
1039         hops.push(RouteHop {
1040                 pubkey: nodes[2].node.get_our_node_id(),
1041                 node_features: NodeFeatures::empty(),
1042                 short_channel_id: chan_3.0.contents.short_channel_id,
1043                 channel_features: ChannelFeatures::empty(),
1044                 fee_msat: 0,
1045                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1046         });
1047         hops.push(RouteHop {
1048                 pubkey: nodes[1].node.get_our_node_id(),
1049                 node_features: NodeFeatures::known(),
1050                 short_channel_id: chan_2.0.contents.short_channel_id,
1051                 channel_features: ChannelFeatures::known(),
1052                 fee_msat: 1000000,
1053                 cltv_expiry_delta: TEST_FINAL_CLTV,
1054         });
1055         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;
1056         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;
1057         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;
1058
1059         // Claim the rebalances...
1060         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1061         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1062
1063         // Add a duplicate new channel from 2 to 4
1064         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1065
1066         // Send some payments across both channels
1067         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1068         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1069         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1070
1071
1072         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1073         let events = nodes[0].node.get_and_clear_pending_msg_events();
1074         assert_eq!(events.len(), 0);
1075         nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1076
1077         //TODO: Test that routes work again here as we've been notified that the channel is full
1078
1079         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1080         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1081         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1082
1083         // Close down the channels...
1084         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1085         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1086         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1087         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1088         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1089         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1090         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1091         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1092         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1093         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1094         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1095         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1096         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1097         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1098         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1099 }
1100
1101 #[test]
1102 fn holding_cell_htlc_counting() {
1103         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1104         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1105         // commitment dance rounds.
1106         let chanmon_cfgs = create_chanmon_cfgs(3);
1107         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1108         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1109         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1110         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1111         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1112
1113         let mut payments = Vec::new();
1114         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1115                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1116                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1117                 payments.push((payment_preimage, payment_hash));
1118         }
1119         check_added_monitors!(nodes[1], 1);
1120
1121         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1122         assert_eq!(events.len(), 1);
1123         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1124         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1125
1126         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1127         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1128         // another HTLC.
1129         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1130         {
1131                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1132                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1133                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1134                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1135         }
1136
1137         // This should also be true if we try to forward a payment.
1138         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1139         {
1140                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1141                 check_added_monitors!(nodes[0], 1);
1142         }
1143
1144         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1145         assert_eq!(events.len(), 1);
1146         let payment_event = SendEvent::from_event(events.pop().unwrap());
1147         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1148
1149         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1150         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1151         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1152         // fails), the second will process the resulting failure and fail the HTLC backward.
1153         expect_pending_htlcs_forwardable!(nodes[1]);
1154         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 }]);
1155         check_added_monitors!(nodes[1], 1);
1156
1157         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1158         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1159         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1160
1161         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1162
1163         // Now forward all the pending HTLCs and claim them back
1164         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1165         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1166         check_added_monitors!(nodes[2], 1);
1167
1168         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1169         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1170         check_added_monitors!(nodes[1], 1);
1171         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1172
1173         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1174         check_added_monitors!(nodes[1], 1);
1175         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1176
1177         for ref update in as_updates.update_add_htlcs.iter() {
1178                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1179         }
1180         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1181         check_added_monitors!(nodes[2], 1);
1182         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1183         check_added_monitors!(nodes[2], 1);
1184         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1185
1186         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1187         check_added_monitors!(nodes[1], 1);
1188         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1189         check_added_monitors!(nodes[1], 1);
1190         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1191
1192         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1193         check_added_monitors!(nodes[2], 1);
1194
1195         expect_pending_htlcs_forwardable!(nodes[2]);
1196
1197         let events = nodes[2].node.get_and_clear_pending_events();
1198         assert_eq!(events.len(), payments.len());
1199         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1200                 match event {
1201                         &Event::PaymentReceived { ref payment_hash, .. } => {
1202                                 assert_eq!(*payment_hash, *hash);
1203                         },
1204                         _ => panic!("Unexpected event"),
1205                 };
1206         }
1207
1208         for (preimage, _) in payments.drain(..) {
1209                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1210         }
1211
1212         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1213 }
1214
1215 #[test]
1216 fn duplicate_htlc_test() {
1217         // Test that we accept duplicate payment_hash HTLCs across the network and that
1218         // claiming/failing them are all separate and don't affect each other
1219         let chanmon_cfgs = create_chanmon_cfgs(6);
1220         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1221         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1222         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1223
1224         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1225         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1226         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1227         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1228         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1229         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1230
1231         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1232
1233         *nodes[0].network_payment_count.borrow_mut() -= 1;
1234         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1235
1236         *nodes[0].network_payment_count.borrow_mut() -= 1;
1237         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1238
1239         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1240         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1241         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1242 }
1243
1244 #[test]
1245 fn test_duplicate_htlc_different_direction_onchain() {
1246         // Test that ChannelMonitor doesn't generate 2 preimage txn
1247         // when we have 2 HTLCs with same preimage that go across a node
1248         // in opposite directions, even with the same payment secret.
1249         let chanmon_cfgs = create_chanmon_cfgs(2);
1250         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1251         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1252         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1253
1254         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1255
1256         // balancing
1257         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1258
1259         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1260
1261         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1262         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1263         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1264
1265         // Provide preimage to node 0 by claiming payment
1266         nodes[0].node.claim_funds(payment_preimage);
1267         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1268         check_added_monitors!(nodes[0], 1);
1269
1270         // Broadcast node 1 commitment txn
1271         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1272
1273         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1274         let mut has_both_htlcs = 0; // check htlcs match ones committed
1275         for outp in remote_txn[0].output.iter() {
1276                 if outp.value == 800_000 / 1000 {
1277                         has_both_htlcs += 1;
1278                 } else if outp.value == 900_000 / 1000 {
1279                         has_both_htlcs += 1;
1280                 }
1281         }
1282         assert_eq!(has_both_htlcs, 2);
1283
1284         mine_transaction(&nodes[0], &remote_txn[0]);
1285         check_added_monitors!(nodes[0], 1);
1286         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1287         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1288
1289         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1290         assert_eq!(claim_txn.len(), 8);
1291
1292         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1293
1294         check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1295         check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1296
1297         let bump_tx = if claim_txn[1] == claim_txn[4] {
1298                 assert_eq!(claim_txn[1], claim_txn[4]);
1299                 assert_eq!(claim_txn[2], claim_txn[5]);
1300
1301                 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1302
1303                 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1304                 &claim_txn[3]
1305         } else {
1306                 assert_eq!(claim_txn[1], claim_txn[3]);
1307                 assert_eq!(claim_txn[2], claim_txn[4]);
1308
1309                 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1310
1311                 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1312
1313                 &claim_txn[7]
1314         };
1315
1316         assert_eq!(claim_txn[0].input.len(), 1);
1317         assert_eq!(bump_tx.input.len(), 1);
1318         assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1319
1320         assert_eq!(claim_txn[0].input.len(), 1);
1321         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1322         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1323
1324         assert_eq!(claim_txn[6].input.len(), 1);
1325         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1326         check_spends!(claim_txn[6], remote_txn[0]);
1327         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1328
1329         let events = nodes[0].node.get_and_clear_pending_msg_events();
1330         assert_eq!(events.len(), 3);
1331         for e in events {
1332                 match e {
1333                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1334                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1335                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1336                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1337                         },
1338                         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, .. } } => {
1339                                 assert!(update_add_htlcs.is_empty());
1340                                 assert!(update_fail_htlcs.is_empty());
1341                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1342                                 assert!(update_fail_malformed_htlcs.is_empty());
1343                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1344                         },
1345                         _ => panic!("Unexpected event"),
1346                 }
1347         }
1348 }
1349
1350 #[test]
1351 fn test_basic_channel_reserve() {
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, InitFeatures::known(), InitFeatures::known());
1357
1358         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1359         let channel_reserve = chan_stat.channel_reserve_msat;
1360
1361         // The 2* and +1 are for the fee spike reserve.
1362         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1363         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1364         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1365         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1366         match err {
1367                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1368                         match &fails[0] {
1369                                 &APIError::ChannelUnavailable{ref err} =>
1370                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1371                                 _ => panic!("Unexpected error variant"),
1372                         }
1373                 },
1374                 _ => panic!("Unexpected error variant"),
1375         }
1376         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1377         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);
1378
1379         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1380 }
1381
1382 #[test]
1383 fn test_fee_spike_violation_fails_htlc() {
1384         let chanmon_cfgs = create_chanmon_cfgs(2);
1385         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1386         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1387         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1388         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1389
1390         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1391         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1392         let secp_ctx = Secp256k1::new();
1393         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1394
1395         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1396
1397         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1398         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1399         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1400         let msg = msgs::UpdateAddHTLC {
1401                 channel_id: chan.2,
1402                 htlc_id: 0,
1403                 amount_msat: htlc_msat,
1404                 payment_hash: payment_hash,
1405                 cltv_expiry: htlc_cltv,
1406                 onion_routing_packet: onion_packet,
1407         };
1408
1409         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1410
1411         // Now manually create the commitment_signed message corresponding to the update_add
1412         // nodes[0] just sent. In the code for construction of this message, "local" refers
1413         // to the sender of the message, and "remote" refers to the receiver.
1414
1415         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1416
1417         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1418
1419         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1420         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1421         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1422                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1423                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1424                 let chan_signer = local_chan.get_signer();
1425                 // Make the signer believe we validated another commitment, so we can release the secret
1426                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1427
1428                 let pubkeys = chan_signer.pubkeys();
1429                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1430                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1431                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1432                  chan_signer.pubkeys().funding_pubkey)
1433         };
1434         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1435                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1436                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1437                 let chan_signer = remote_chan.get_signer();
1438                 let pubkeys = chan_signer.pubkeys();
1439                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1440                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1441                  chan_signer.pubkeys().funding_pubkey)
1442         };
1443
1444         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1445         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1446                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1447
1448         // Build the remote commitment transaction so we can sign it, and then later use the
1449         // signature for the commitment_signed message.
1450         let local_chan_balance = 1313;
1451
1452         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1453                 offered: false,
1454                 amount_msat: 3460001,
1455                 cltv_expiry: htlc_cltv,
1456                 payment_hash,
1457                 transaction_output_index: Some(1),
1458         };
1459
1460         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1461
1462         let res = {
1463                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1464                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1465                 let local_chan_signer = local_chan.get_signer();
1466                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1467                         commitment_number,
1468                         95000,
1469                         local_chan_balance,
1470                         local_chan.opt_anchors(), local_funding, remote_funding,
1471                         commit_tx_keys.clone(),
1472                         feerate_per_kw,
1473                         &mut vec![(accepted_htlc_info, ())],
1474                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1475                 );
1476                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1477         };
1478
1479         let commit_signed_msg = msgs::CommitmentSigned {
1480                 channel_id: chan.2,
1481                 signature: res.0,
1482                 htlc_signatures: res.1
1483         };
1484
1485         // Send the commitment_signed message to the nodes[1].
1486         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1487         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1488
1489         // Send the RAA to nodes[1].
1490         let raa_msg = msgs::RevokeAndACK {
1491                 channel_id: chan.2,
1492                 per_commitment_secret: local_secret,
1493                 next_per_commitment_point: next_local_point
1494         };
1495         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1496
1497         let events = nodes[1].node.get_and_clear_pending_msg_events();
1498         assert_eq!(events.len(), 1);
1499         // Make sure the HTLC failed in the way we expect.
1500         match events[0] {
1501                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1502                         assert_eq!(update_fail_htlcs.len(), 1);
1503                         update_fail_htlcs[0].clone()
1504                 },
1505                 _ => panic!("Unexpected event"),
1506         };
1507         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1508                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1509
1510         check_added_monitors!(nodes[1], 2);
1511 }
1512
1513 #[test]
1514 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1515         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1516         // Set the fee rate for the channel very high, to the point where the fundee
1517         // sending any above-dust amount would result in a channel reserve violation.
1518         // In this test we check that we would be prevented from sending an HTLC in
1519         // this situation.
1520         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1521         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1522         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1523         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1524
1525         let opt_anchors = false;
1526
1527         let mut push_amt = 100_000_000;
1528         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1529         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1530
1531         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1532
1533         // Sending exactly enough to hit the reserve amount should be accepted
1534         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1535                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1536         }
1537
1538         // However one more HTLC should be significantly over the reserve amount and fail.
1539         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1540         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1541                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1542         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1543         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);
1544 }
1545
1546 #[test]
1547 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1548         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1549         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1550         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1551         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1552         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1553
1554         let opt_anchors = false;
1555
1556         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1557         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1558         // transaction fee with 0 HTLCs (183 sats)).
1559         let mut push_amt = 100_000_000;
1560         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1561         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1562         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1563
1564         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1565         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1566                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1567         }
1568
1569         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1570         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1571         let secp_ctx = Secp256k1::new();
1572         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1573         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1574         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1575         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1576         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1577         let msg = msgs::UpdateAddHTLC {
1578                 channel_id: chan.2,
1579                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1580                 amount_msat: htlc_msat,
1581                 payment_hash: payment_hash,
1582                 cltv_expiry: htlc_cltv,
1583                 onion_routing_packet: onion_packet,
1584         };
1585
1586         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1587         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1588         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);
1589         assert_eq!(nodes[0].node.list_channels().len(), 0);
1590         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1591         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1592         check_added_monitors!(nodes[0], 1);
1593         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() });
1594 }
1595
1596 #[test]
1597 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1598         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1599         // calculating our commitment transaction fee (this was previously broken).
1600         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1601         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1602
1603         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1604         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1605         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1606
1607         let opt_anchors = false;
1608
1609         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1610         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1611         // transaction fee with 0 HTLCs (183 sats)).
1612         let mut push_amt = 100_000_000;
1613         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1614         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1615         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1616
1617         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1618                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1619         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1620         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1621         // commitment transaction fee.
1622         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1623
1624         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1625         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1626                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1627         }
1628
1629         // One more than the dust amt should fail, however.
1630         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1631         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1632                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1633 }
1634
1635 #[test]
1636 fn test_chan_init_feerate_unaffordability() {
1637         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1638         // channel reserve and feerate requirements.
1639         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1640         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1641         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1642         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1643         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1644
1645         let opt_anchors = false;
1646
1647         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1648         // HTLC.
1649         let mut push_amt = 100_000_000;
1650         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1651         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1652                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1653
1654         // During open, we don't have a "counterparty channel reserve" to check against, so that
1655         // requirement only comes into play on the open_channel handling side.
1656         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1657         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1658         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1659         open_channel_msg.push_msat += 1;
1660         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1661
1662         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1663         assert_eq!(msg_events.len(), 1);
1664         match msg_events[0] {
1665                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1666                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1667                 },
1668                 _ => panic!("Unexpected event"),
1669         }
1670 }
1671
1672 #[test]
1673 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1674         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1675         // calculating our counterparty's commitment transaction fee (this was previously broken).
1676         let chanmon_cfgs = create_chanmon_cfgs(2);
1677         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1678         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1679         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1680         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1681
1682         let payment_amt = 46000; // Dust amount
1683         // In the previous code, these first four payments would succeed.
1684         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1686         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1688
1689         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1690         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1691         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1693         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1694         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1695
1696         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1697         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1698         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1699         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1700 }
1701
1702 #[test]
1703 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1704         let chanmon_cfgs = create_chanmon_cfgs(3);
1705         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1706         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1707         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1708         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1709         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1710
1711         let feemsat = 239;
1712         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1713         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1714         let feerate = get_feerate!(nodes[0], chan.2);
1715         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1716
1717         // Add a 2* and +1 for the fee spike reserve.
1718         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1719         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;
1720         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1721
1722         // Add a pending HTLC.
1723         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1724         let payment_event_1 = {
1725                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1726                 check_added_monitors!(nodes[0], 1);
1727
1728                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1729                 assert_eq!(events.len(), 1);
1730                 SendEvent::from_event(events.remove(0))
1731         };
1732         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1733
1734         // Attempt to trigger a channel reserve violation --> payment failure.
1735         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1736         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;
1737         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1738         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1739
1740         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1741         let secp_ctx = Secp256k1::new();
1742         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1743         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1744         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1745         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1746         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1747         let msg = msgs::UpdateAddHTLC {
1748                 channel_id: chan.2,
1749                 htlc_id: 1,
1750                 amount_msat: htlc_msat + 1,
1751                 payment_hash: our_payment_hash_1,
1752                 cltv_expiry: htlc_cltv,
1753                 onion_routing_packet: onion_packet,
1754         };
1755
1756         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1757         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1758         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1759         assert_eq!(nodes[1].node.list_channels().len(), 1);
1760         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1761         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1762         check_added_monitors!(nodes[1], 1);
1763         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1764 }
1765
1766 #[test]
1767 fn test_inbound_outbound_capacity_is_not_zero() {
1768         let chanmon_cfgs = create_chanmon_cfgs(2);
1769         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1770         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1771         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1772         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1773         let channels0 = node_chanmgrs[0].list_channels();
1774         let channels1 = node_chanmgrs[1].list_channels();
1775         assert_eq!(channels0.len(), 1);
1776         assert_eq!(channels1.len(), 1);
1777
1778         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1779         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1780         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1781
1782         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1783         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1784 }
1785
1786 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1787         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1788 }
1789
1790 #[test]
1791 fn test_channel_reserve_holding_cell_htlcs() {
1792         let chanmon_cfgs = create_chanmon_cfgs(3);
1793         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1794         // When this test was written, the default base fee floated based on the HTLC count.
1795         // It is now fixed, so we simply set the fee to the expected value here.
1796         let mut config = test_default_channel_config();
1797         config.channel_config.forwarding_fee_base_msat = 239;
1798         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1799         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1800         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1801         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1802
1803         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1804         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1805
1806         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1807         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1808
1809         macro_rules! expect_forward {
1810                 ($node: expr) => {{
1811                         let mut events = $node.node.get_and_clear_pending_msg_events();
1812                         assert_eq!(events.len(), 1);
1813                         check_added_monitors!($node, 1);
1814                         let payment_event = SendEvent::from_event(events.remove(0));
1815                         payment_event
1816                 }}
1817         }
1818
1819         let feemsat = 239; // set above
1820         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1821         let feerate = get_feerate!(nodes[0], chan_1.2);
1822         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1823
1824         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1825
1826         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1827         {
1828                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1829                         .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1830                 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);
1831                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1832                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1833
1834                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1835                         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)));
1836                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1837                 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);
1838         }
1839
1840         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1841         // nodes[0]'s wealth
1842         loop {
1843                 let amt_msat = recv_value_0 + total_fee_msat;
1844                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1845                 // Also, ensure that each payment has enough to be over the dust limit to
1846                 // ensure it'll be included in each commit tx fee calculation.
1847                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1848                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1849                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1850                         break;
1851                 }
1852
1853                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1854                         .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1855                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1856                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1857                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1858
1859                 let (stat01_, stat11_, stat12_, stat22_) = (
1860                         get_channel_value_stat!(nodes[0], chan_1.2),
1861                         get_channel_value_stat!(nodes[1], chan_1.2),
1862                         get_channel_value_stat!(nodes[1], chan_2.2),
1863                         get_channel_value_stat!(nodes[2], chan_2.2),
1864                 );
1865
1866                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1867                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1868                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1869                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1870                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1871         }
1872
1873         // adding pending output.
1874         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1875         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1876         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1877         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1878         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1879         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1880         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1881         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1882         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1883         // policy.
1884         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1885         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1886         let amt_msat_1 = recv_value_1 + total_fee_msat;
1887
1888         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);
1889         let payment_event_1 = {
1890                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1891                 check_added_monitors!(nodes[0], 1);
1892
1893                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1894                 assert_eq!(events.len(), 1);
1895                 SendEvent::from_event(events.remove(0))
1896         };
1897         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1898
1899         // channel reserve test with htlc pending output > 0
1900         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1901         {
1902                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1903                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1904                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1905                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1906         }
1907
1908         // split the rest to test holding cell
1909         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1910         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1911         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1912         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1913         {
1914                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1915                 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);
1916         }
1917
1918         // now see if they go through on both sides
1919         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);
1920         // but this will stuck in the holding cell
1921         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1922         check_added_monitors!(nodes[0], 0);
1923         let events = nodes[0].node.get_and_clear_pending_events();
1924         assert_eq!(events.len(), 0);
1925
1926         // test with outbound holding cell amount > 0
1927         {
1928                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1929                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1930                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1931                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1932                 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);
1933         }
1934
1935         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);
1936         // this will also stuck in the holding cell
1937         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1938         check_added_monitors!(nodes[0], 0);
1939         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1940         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1941
1942         // flush the pending htlc
1943         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1944         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1945         check_added_monitors!(nodes[1], 1);
1946
1947         // the pending htlc should be promoted to committed
1948         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1949         check_added_monitors!(nodes[0], 1);
1950         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1951
1952         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1953         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1954         // No commitment_signed so get_event_msg's assert(len == 1) passes
1955         check_added_monitors!(nodes[0], 1);
1956
1957         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1958         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1959         check_added_monitors!(nodes[1], 1);
1960
1961         expect_pending_htlcs_forwardable!(nodes[1]);
1962
1963         let ref payment_event_11 = expect_forward!(nodes[1]);
1964         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1965         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1966
1967         expect_pending_htlcs_forwardable!(nodes[2]);
1968         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1969
1970         // flush the htlcs in the holding cell
1971         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1972         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1973         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1974         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1975         expect_pending_htlcs_forwardable!(nodes[1]);
1976
1977         let ref payment_event_3 = expect_forward!(nodes[1]);
1978         assert_eq!(payment_event_3.msgs.len(), 2);
1979         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1980         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1981
1982         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1983         expect_pending_htlcs_forwardable!(nodes[2]);
1984
1985         let events = nodes[2].node.get_and_clear_pending_events();
1986         assert_eq!(events.len(), 2);
1987         match events[0] {
1988                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1989                         assert_eq!(our_payment_hash_21, *payment_hash);
1990                         assert_eq!(recv_value_21, amount_msat);
1991                         match &purpose {
1992                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1993                                         assert!(payment_preimage.is_none());
1994                                         assert_eq!(our_payment_secret_21, *payment_secret);
1995                                 },
1996                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1997                         }
1998                 },
1999                 _ => panic!("Unexpected event"),
2000         }
2001         match events[1] {
2002                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
2003                         assert_eq!(our_payment_hash_22, *payment_hash);
2004                         assert_eq!(recv_value_22, amount_msat);
2005                         match &purpose {
2006                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2007                                         assert!(payment_preimage.is_none());
2008                                         assert_eq!(our_payment_secret_22, *payment_secret);
2009                                 },
2010                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2011                         }
2012                 },
2013                 _ => panic!("Unexpected event"),
2014         }
2015
2016         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2017         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2018         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2019
2020         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2021         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2022         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2023
2024         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2025         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);
2026         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2027         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2028         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2029
2030         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2031         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2032 }
2033
2034 #[test]
2035 fn channel_reserve_in_flight_removes() {
2036         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2037         // can send to its counterparty, but due to update ordering, the other side may not yet have
2038         // considered those HTLCs fully removed.
2039         // This tests that we don't count HTLCs which will not be included in the next remote
2040         // commitment transaction towards the reserve value (as it implies no commitment transaction
2041         // will be generated which violates the remote reserve value).
2042         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2043         // To test this we:
2044         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2045         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2046         //    you only consider the value of the first HTLC, it may not),
2047         //  * start routing a third HTLC from A to B,
2048         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2049         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2050         //  * deliver the first fulfill from B
2051         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2052         //    claim,
2053         //  * deliver A's response CS and RAA.
2054         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2055         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2056         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2057         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2058         let chanmon_cfgs = create_chanmon_cfgs(2);
2059         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2060         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2061         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2062         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2063
2064         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2065         // Route the first two HTLCs.
2066         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2067         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2068         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2069
2070         // Start routing the third HTLC (this is just used to get everyone in the right state).
2071         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2072         let send_1 = {
2073                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2074                 check_added_monitors!(nodes[0], 1);
2075                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2076                 assert_eq!(events.len(), 1);
2077                 SendEvent::from_event(events.remove(0))
2078         };
2079
2080         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2081         // initial fulfill/CS.
2082         nodes[1].node.claim_funds(payment_preimage_1);
2083         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2084         check_added_monitors!(nodes[1], 1);
2085         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2086
2087         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2088         // remove the second HTLC when we send the HTLC back from B to A.
2089         nodes[1].node.claim_funds(payment_preimage_2);
2090         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2091         check_added_monitors!(nodes[1], 1);
2092         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2093
2094         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2095         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2096         check_added_monitors!(nodes[0], 1);
2097         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2098         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2099
2100         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2101         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2102         check_added_monitors!(nodes[1], 1);
2103         // B is already AwaitingRAA, so cant generate a CS here
2104         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2105
2106         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2107         check_added_monitors!(nodes[1], 1);
2108         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2109
2110         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2111         check_added_monitors!(nodes[0], 1);
2112         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2113
2114         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2115         check_added_monitors!(nodes[1], 1);
2116         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2117
2118         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2119         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2120         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2121         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2122         // on-chain as necessary).
2123         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2124         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2125         check_added_monitors!(nodes[0], 1);
2126         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2127         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2128
2129         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2130         check_added_monitors!(nodes[1], 1);
2131         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2132
2133         expect_pending_htlcs_forwardable!(nodes[1]);
2134         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2135
2136         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2137         // resolve the second HTLC from A's point of view.
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         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2144         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2145         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2146         let send_2 = {
2147                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2148                 check_added_monitors!(nodes[1], 1);
2149                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2150                 assert_eq!(events.len(), 1);
2151                 SendEvent::from_event(events.remove(0))
2152         };
2153
2154         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2155         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2156         check_added_monitors!(nodes[0], 1);
2157         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2158
2159         // Now just resolve all the outstanding messages/HTLCs for completeness...
2160
2161         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2162         check_added_monitors!(nodes[1], 1);
2163         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2164
2165         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2166         check_added_monitors!(nodes[1], 1);
2167
2168         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2169         check_added_monitors!(nodes[0], 1);
2170         expect_payment_path_successful!(nodes[0]);
2171         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2172
2173         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2174         check_added_monitors!(nodes[1], 1);
2175         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2176
2177         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2178         check_added_monitors!(nodes[0], 1);
2179
2180         expect_pending_htlcs_forwardable!(nodes[0]);
2181         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2182
2183         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2184         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2185 }
2186
2187 #[test]
2188 fn channel_monitor_network_test() {
2189         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2190         // tests that ChannelMonitor is able to recover from various states.
2191         let chanmon_cfgs = create_chanmon_cfgs(5);
2192         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2193         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2194         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2195
2196         // Create some initial channels
2197         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2198         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2199         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2200         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2201
2202         // Make sure all nodes are at the same starting height
2203         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2204         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2205         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2206         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2207         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2208
2209         // Rebalance the network a bit by relaying one payment through all the channels...
2210         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2211         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2212         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2213         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2214
2215         // Simple case with no pending HTLCs:
2216         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2217         check_added_monitors!(nodes[1], 1);
2218         check_closed_broadcast!(nodes[1], true);
2219         {
2220                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2221                 assert_eq!(node_txn.len(), 1);
2222                 mine_transaction(&nodes[0], &node_txn[0]);
2223                 check_added_monitors!(nodes[0], 1);
2224                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2225         }
2226         check_closed_broadcast!(nodes[0], true);
2227         assert_eq!(nodes[0].node.list_channels().len(), 0);
2228         assert_eq!(nodes[1].node.list_channels().len(), 1);
2229         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2230         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2231
2232         // One pending HTLC is discarded by the force-close:
2233         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2234
2235         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2236         // broadcasted until we reach the timelock time).
2237         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2238         check_closed_broadcast!(nodes[1], true);
2239         check_added_monitors!(nodes[1], 1);
2240         {
2241                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2242                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2243                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2244                 mine_transaction(&nodes[2], &node_txn[0]);
2245                 check_added_monitors!(nodes[2], 1);
2246                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2247         }
2248         check_closed_broadcast!(nodes[2], true);
2249         assert_eq!(nodes[1].node.list_channels().len(), 0);
2250         assert_eq!(nodes[2].node.list_channels().len(), 1);
2251         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2252         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2253
2254         macro_rules! claim_funds {
2255                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2256                         {
2257                                 $node.node.claim_funds($preimage);
2258                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2259                                 check_added_monitors!($node, 1);
2260
2261                                 let events = $node.node.get_and_clear_pending_msg_events();
2262                                 assert_eq!(events.len(), 1);
2263                                 match events[0] {
2264                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2265                                                 assert!(update_add_htlcs.is_empty());
2266                                                 assert!(update_fail_htlcs.is_empty());
2267                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2268                                         },
2269                                         _ => panic!("Unexpected event"),
2270                                 };
2271                         }
2272                 }
2273         }
2274
2275         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2276         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2277         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2278         check_added_monitors!(nodes[2], 1);
2279         check_closed_broadcast!(nodes[2], true);
2280         let node2_commitment_txid;
2281         {
2282                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2283                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2284                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2285                 node2_commitment_txid = node_txn[0].txid();
2286
2287                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2288                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2289                 mine_transaction(&nodes[3], &node_txn[0]);
2290                 check_added_monitors!(nodes[3], 1);
2291                 check_preimage_claim(&nodes[3], &node_txn);
2292         }
2293         check_closed_broadcast!(nodes[3], true);
2294         assert_eq!(nodes[2].node.list_channels().len(), 0);
2295         assert_eq!(nodes[3].node.list_channels().len(), 1);
2296         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2297         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2298
2299         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2300         // confusing us in the following tests.
2301         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2302
2303         // One pending HTLC to time out:
2304         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2305         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2306         // buffer space).
2307
2308         let (close_chan_update_1, close_chan_update_2) = {
2309                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2310                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2311                 assert_eq!(events.len(), 2);
2312                 let close_chan_update_1 = match events[0] {
2313                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2314                                 msg.clone()
2315                         },
2316                         _ => panic!("Unexpected event"),
2317                 };
2318                 match events[1] {
2319                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2320                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2321                         },
2322                         _ => panic!("Unexpected event"),
2323                 }
2324                 check_added_monitors!(nodes[3], 1);
2325
2326                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2327                 {
2328                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2329                         node_txn.retain(|tx| {
2330                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2331                                         false
2332                                 } else { true }
2333                         });
2334                 }
2335
2336                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2337
2338                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2339                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2340
2341                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2342                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2343                 assert_eq!(events.len(), 2);
2344                 let close_chan_update_2 = match events[0] {
2345                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2346                                 msg.clone()
2347                         },
2348                         _ => panic!("Unexpected event"),
2349                 };
2350                 match events[1] {
2351                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2352                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2353                         },
2354                         _ => panic!("Unexpected event"),
2355                 }
2356                 check_added_monitors!(nodes[4], 1);
2357                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2358
2359                 mine_transaction(&nodes[4], &node_txn[0]);
2360                 check_preimage_claim(&nodes[4], &node_txn);
2361                 (close_chan_update_1, close_chan_update_2)
2362         };
2363         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2364         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2365         assert_eq!(nodes[3].node.list_channels().len(), 0);
2366         assert_eq!(nodes[4].node.list_channels().len(), 0);
2367
2368         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2369         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2370         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2371 }
2372
2373 #[test]
2374 fn test_justice_tx() {
2375         // Test justice txn built on revoked HTLC-Success tx, against both sides
2376         let mut alice_config = UserConfig::default();
2377         alice_config.channel_handshake_config.announced_channel = true;
2378         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2379         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2380         let mut bob_config = UserConfig::default();
2381         bob_config.channel_handshake_config.announced_channel = true;
2382         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2383         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2384         let user_cfgs = [Some(alice_config), Some(bob_config)];
2385         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2386         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2387         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2388         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2389         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2390         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2391         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2392         // Create some new channels:
2393         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2394
2395         // A pending HTLC which will be revoked:
2396         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2397         // Get the will-be-revoked local txn from nodes[0]
2398         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2399         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2400         assert_eq!(revoked_local_txn[0].input.len(), 1);
2401         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2402         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2403         assert_eq!(revoked_local_txn[1].input.len(), 1);
2404         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2405         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2406         // Revoke the old state
2407         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2408
2409         {
2410                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2411                 {
2412                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2413                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2414                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2415
2416                         check_spends!(node_txn[0], revoked_local_txn[0]);
2417                         node_txn.swap_remove(0);
2418                         node_txn.truncate(1);
2419                 }
2420                 check_added_monitors!(nodes[1], 1);
2421                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2422                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2423
2424                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2425                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2426                 // Verify broadcast of revoked HTLC-timeout
2427                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2428                 check_added_monitors!(nodes[0], 1);
2429                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2430                 // Broadcast revoked HTLC-timeout on node 1
2431                 mine_transaction(&nodes[1], &node_txn[1]);
2432                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2433         }
2434         get_announce_close_broadcast_events(&nodes, 0, 1);
2435
2436         assert_eq!(nodes[0].node.list_channels().len(), 0);
2437         assert_eq!(nodes[1].node.list_channels().len(), 0);
2438
2439         // We test justice_tx build by A on B's revoked HTLC-Success tx
2440         // Create some new channels:
2441         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2442         {
2443                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2444                 node_txn.clear();
2445         }
2446
2447         // A pending HTLC which will be revoked:
2448         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2449         // Get the will-be-revoked local txn from B
2450         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2451         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2452         assert_eq!(revoked_local_txn[0].input.len(), 1);
2453         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2454         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2455         // Revoke the old state
2456         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2457         {
2458                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2459                 {
2460                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2461                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2462                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2463
2464                         check_spends!(node_txn[0], revoked_local_txn[0]);
2465                         node_txn.swap_remove(0);
2466                 }
2467                 check_added_monitors!(nodes[0], 1);
2468                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2469
2470                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2471                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2472                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2473                 check_added_monitors!(nodes[1], 1);
2474                 mine_transaction(&nodes[0], &node_txn[1]);
2475                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2476                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2477         }
2478         get_announce_close_broadcast_events(&nodes, 0, 1);
2479         assert_eq!(nodes[0].node.list_channels().len(), 0);
2480         assert_eq!(nodes[1].node.list_channels().len(), 0);
2481 }
2482
2483 #[test]
2484 fn revoked_output_claim() {
2485         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2486         // transaction is broadcast by its counterparty
2487         let chanmon_cfgs = create_chanmon_cfgs(2);
2488         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2489         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2490         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2491         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2492         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2493         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2494         assert_eq!(revoked_local_txn.len(), 1);
2495         // Only output is the full channel value back to nodes[0]:
2496         assert_eq!(revoked_local_txn[0].output.len(), 1);
2497         // Send a payment through, updating everyone's latest commitment txn
2498         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2499
2500         // Inform nodes[1] that nodes[0] broadcast a stale tx
2501         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2502         check_added_monitors!(nodes[1], 1);
2503         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2504         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2505         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2506
2507         check_spends!(node_txn[0], revoked_local_txn[0]);
2508         check_spends!(node_txn[1], chan_1.3);
2509
2510         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2511         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2512         get_announce_close_broadcast_events(&nodes, 0, 1);
2513         check_added_monitors!(nodes[0], 1);
2514         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2515 }
2516
2517 #[test]
2518 fn claim_htlc_outputs_shared_tx() {
2519         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2520         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2521         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2522         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2523         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2524         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2525
2526         // Create some new channel:
2527         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2528
2529         // Rebalance the network to generate htlc in the two directions
2530         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2531         // 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
2532         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2533         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2534
2535         // Get the will-be-revoked local txn from node[0]
2536         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2537         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2538         assert_eq!(revoked_local_txn[0].input.len(), 1);
2539         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2540         assert_eq!(revoked_local_txn[1].input.len(), 1);
2541         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2542         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2543         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2544
2545         //Revoke the old state
2546         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2547
2548         {
2549                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2550                 check_added_monitors!(nodes[0], 1);
2551                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2552                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2553                 check_added_monitors!(nodes[1], 1);
2554                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2555                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2556                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2557
2558                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2559                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2560
2561                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2562                 check_spends!(node_txn[0], revoked_local_txn[0]);
2563
2564                 let mut witness_lens = BTreeSet::new();
2565                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2566                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2567                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2568                 assert_eq!(witness_lens.len(), 3);
2569                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2570                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2571                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2572
2573                 // Next nodes[1] broadcasts its current local tx state:
2574                 assert_eq!(node_txn[1].input.len(), 1);
2575                 check_spends!(node_txn[1], chan_1.3);
2576
2577                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2578                 // ANTI_REORG_DELAY confirmations.
2579                 mine_transaction(&nodes[1], &node_txn[0]);
2580                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2581                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2582         }
2583         get_announce_close_broadcast_events(&nodes, 0, 1);
2584         assert_eq!(nodes[0].node.list_channels().len(), 0);
2585         assert_eq!(nodes[1].node.list_channels().len(), 0);
2586 }
2587
2588 #[test]
2589 fn claim_htlc_outputs_single_tx() {
2590         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2591         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2592         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2593         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2594         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2595         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2596
2597         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2598
2599         // Rebalance the network to generate htlc in the two directions
2600         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2601         // 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
2602         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2603         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2604         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2605
2606         // Get the will-be-revoked local txn from node[0]
2607         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2608
2609         //Revoke the old state
2610         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2611
2612         {
2613                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2614                 check_added_monitors!(nodes[0], 1);
2615                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2616                 check_added_monitors!(nodes[1], 1);
2617                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2618                 let mut events = nodes[0].node.get_and_clear_pending_events();
2619                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2620                 match events.last().unwrap() {
2621                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2622                         _ => panic!("Unexpected event"),
2623                 }
2624
2625                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2626                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2627
2628                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2629                 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2630
2631                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2632                 assert_eq!(node_txn[0].input.len(), 1);
2633                 check_spends!(node_txn[0], chan_1.3);
2634                 assert_eq!(node_txn[1].input.len(), 1);
2635                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2636                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2637                 check_spends!(node_txn[1], node_txn[0]);
2638
2639                 // Justice transactions are indices 1-2-4
2640                 assert_eq!(node_txn[2].input.len(), 1);
2641                 assert_eq!(node_txn[3].input.len(), 1);
2642                 assert_eq!(node_txn[4].input.len(), 1);
2643
2644                 check_spends!(node_txn[2], revoked_local_txn[0]);
2645                 check_spends!(node_txn[3], revoked_local_txn[0]);
2646                 check_spends!(node_txn[4], revoked_local_txn[0]);
2647
2648                 let mut witness_lens = BTreeSet::new();
2649                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2650                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2651                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2652                 assert_eq!(witness_lens.len(), 3);
2653                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2654                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2655                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2656
2657                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2658                 // ANTI_REORG_DELAY confirmations.
2659                 mine_transaction(&nodes[1], &node_txn[2]);
2660                 mine_transaction(&nodes[1], &node_txn[3]);
2661                 mine_transaction(&nodes[1], &node_txn[4]);
2662                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2663                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2664         }
2665         get_announce_close_broadcast_events(&nodes, 0, 1);
2666         assert_eq!(nodes[0].node.list_channels().len(), 0);
2667         assert_eq!(nodes[1].node.list_channels().len(), 0);
2668 }
2669
2670 #[test]
2671 fn test_htlc_on_chain_success() {
2672         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2673         // the preimage backward accordingly. So here we test that ChannelManager is
2674         // broadcasting the right event to other nodes in payment path.
2675         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2676         // A --------------------> B ----------------------> C (preimage)
2677         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2678         // commitment transaction was broadcast.
2679         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2680         // towards B.
2681         // B should be able to claim via preimage if A then broadcasts its local tx.
2682         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2683         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2684         // PaymentSent event).
2685
2686         let chanmon_cfgs = create_chanmon_cfgs(3);
2687         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2688         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2689         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2690
2691         // Create some initial channels
2692         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2693         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2694
2695         // Ensure all nodes are at the same height
2696         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2697         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2698         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2699         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2700
2701         // Rebalance the network a bit by relaying one payment through all the channels...
2702         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2703         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2704
2705         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2706         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2707
2708         // Broadcast legit commitment tx from C on B's chain
2709         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2710         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2711         assert_eq!(commitment_tx.len(), 1);
2712         check_spends!(commitment_tx[0], chan_2.3);
2713         nodes[2].node.claim_funds(our_payment_preimage);
2714         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2715         nodes[2].node.claim_funds(our_payment_preimage_2);
2716         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2717         check_added_monitors!(nodes[2], 2);
2718         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2719         assert!(updates.update_add_htlcs.is_empty());
2720         assert!(updates.update_fail_htlcs.is_empty());
2721         assert!(updates.update_fail_malformed_htlcs.is_empty());
2722         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2723
2724         mine_transaction(&nodes[2], &commitment_tx[0]);
2725         check_closed_broadcast!(nodes[2], true);
2726         check_added_monitors!(nodes[2], 1);
2727         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2728         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)
2729         assert_eq!(node_txn.len(), 5);
2730         assert_eq!(node_txn[0], node_txn[3]);
2731         assert_eq!(node_txn[1], node_txn[4]);
2732         assert_eq!(node_txn[2], commitment_tx[0]);
2733         check_spends!(node_txn[0], commitment_tx[0]);
2734         check_spends!(node_txn[1], commitment_tx[0]);
2735         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2736         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2737         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2738         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2739         assert_eq!(node_txn[0].lock_time, 0);
2740         assert_eq!(node_txn[1].lock_time, 0);
2741
2742         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2743         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2744         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2745         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2746         {
2747                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2748                 assert_eq!(added_monitors.len(), 1);
2749                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2750                 added_monitors.clear();
2751         }
2752         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2753         assert_eq!(forwarded_events.len(), 3);
2754         match forwarded_events[0] {
2755                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2756                 _ => panic!("Unexpected event"),
2757         }
2758         let chan_id = Some(chan_1.2);
2759         match forwarded_events[1] {
2760                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2761                         assert_eq!(fee_earned_msat, Some(1000));
2762                         assert_eq!(prev_channel_id, chan_id);
2763                         assert_eq!(claim_from_onchain_tx, true);
2764                         assert_eq!(next_channel_id, Some(chan_2.2));
2765                 },
2766                 _ => panic!()
2767         }
2768         match forwarded_events[2] {
2769                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2770                         assert_eq!(fee_earned_msat, Some(1000));
2771                         assert_eq!(prev_channel_id, chan_id);
2772                         assert_eq!(claim_from_onchain_tx, true);
2773                         assert_eq!(next_channel_id, Some(chan_2.2));
2774                 },
2775                 _ => panic!()
2776         }
2777         let events = nodes[1].node.get_and_clear_pending_msg_events();
2778         {
2779                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2780                 assert_eq!(added_monitors.len(), 2);
2781                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2782                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2783                 added_monitors.clear();
2784         }
2785         assert_eq!(events.len(), 3);
2786         match events[0] {
2787                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2788                 _ => panic!("Unexpected event"),
2789         }
2790         match events[1] {
2791                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2792                 _ => panic!("Unexpected event"),
2793         }
2794
2795         match events[2] {
2796                 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, .. } } => {
2797                         assert!(update_add_htlcs.is_empty());
2798                         assert!(update_fail_htlcs.is_empty());
2799                         assert_eq!(update_fulfill_htlcs.len(), 1);
2800                         assert!(update_fail_malformed_htlcs.is_empty());
2801                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2802                 },
2803                 _ => panic!("Unexpected event"),
2804         };
2805         macro_rules! check_tx_local_broadcast {
2806                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2807                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2808                         assert_eq!(node_txn.len(), 3);
2809                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2810                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2811                         check_spends!(node_txn[1], $commitment_tx);
2812                         check_spends!(node_txn[2], $commitment_tx);
2813                         assert_ne!(node_txn[1].lock_time, 0);
2814                         assert_ne!(node_txn[2].lock_time, 0);
2815                         if $htlc_offered {
2816                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2817                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2818                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2819                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2820                         } else {
2821                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2822                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2823                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2824                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2825                         }
2826                         check_spends!(node_txn[0], $chan_tx);
2827                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2828                         node_txn.clear();
2829                 } }
2830         }
2831         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2832         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2833         // timeout-claim of the output that nodes[2] just claimed via success.
2834         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2835
2836         // Broadcast legit commitment tx from A on B's chain
2837         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2838         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2839         check_spends!(node_a_commitment_tx[0], chan_1.3);
2840         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2841         check_closed_broadcast!(nodes[1], true);
2842         check_added_monitors!(nodes[1], 1);
2843         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2844         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2845         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2846         let commitment_spend =
2847                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2848                         check_spends!(node_txn[1], commitment_tx[0]);
2849                         check_spends!(node_txn[2], commitment_tx[0]);
2850                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2851                         &node_txn[0]
2852                 } else {
2853                         check_spends!(node_txn[0], commitment_tx[0]);
2854                         check_spends!(node_txn[1], commitment_tx[0]);
2855                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2856                         &node_txn[2]
2857                 };
2858
2859         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2860         assert_eq!(commitment_spend.input.len(), 2);
2861         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2862         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2863         assert_eq!(commitment_spend.lock_time, 0);
2864         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2865         check_spends!(node_txn[3], chan_1.3);
2866         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2867         check_spends!(node_txn[4], node_txn[3]);
2868         check_spends!(node_txn[5], node_txn[3]);
2869         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2870         // we already checked the same situation with A.
2871
2872         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2873         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2874         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2875         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2876         check_closed_broadcast!(nodes[0], true);
2877         check_added_monitors!(nodes[0], 1);
2878         let events = nodes[0].node.get_and_clear_pending_events();
2879         assert_eq!(events.len(), 5);
2880         let mut first_claimed = false;
2881         for event in events {
2882                 match event {
2883                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2884                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2885                                         assert!(!first_claimed);
2886                                         first_claimed = true;
2887                                 } else {
2888                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2889                                         assert_eq!(payment_hash, payment_hash_2);
2890                                 }
2891                         },
2892                         Event::PaymentPathSuccessful { .. } => {},
2893                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2894                         _ => panic!("Unexpected event"),
2895                 }
2896         }
2897         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2898 }
2899
2900 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2901         // Test that in case of a unilateral close onchain, we detect the state of output and
2902         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2903         // broadcasting the right event to other nodes in payment path.
2904         // A ------------------> B ----------------------> C (timeout)
2905         //    B's commitment tx                 C's commitment tx
2906         //            \                                  \
2907         //         B's HTLC timeout tx               B's timeout tx
2908
2909         let chanmon_cfgs = create_chanmon_cfgs(3);
2910         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2911         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2912         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2913         *nodes[0].connect_style.borrow_mut() = connect_style;
2914         *nodes[1].connect_style.borrow_mut() = connect_style;
2915         *nodes[2].connect_style.borrow_mut() = connect_style;
2916
2917         // Create some intial channels
2918         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2919         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2920
2921         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2922         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2923         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2924
2925         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2926
2927         // Broadcast legit commitment tx from C on B's chain
2928         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2929         check_spends!(commitment_tx[0], chan_2.3);
2930         nodes[2].node.fail_htlc_backwards(&payment_hash);
2931         check_added_monitors!(nodes[2], 0);
2932         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2933         check_added_monitors!(nodes[2], 1);
2934
2935         let events = nodes[2].node.get_and_clear_pending_msg_events();
2936         assert_eq!(events.len(), 1);
2937         match events[0] {
2938                 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, .. } } => {
2939                         assert!(update_add_htlcs.is_empty());
2940                         assert!(!update_fail_htlcs.is_empty());
2941                         assert!(update_fulfill_htlcs.is_empty());
2942                         assert!(update_fail_malformed_htlcs.is_empty());
2943                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2944                 },
2945                 _ => panic!("Unexpected event"),
2946         };
2947         mine_transaction(&nodes[2], &commitment_tx[0]);
2948         check_closed_broadcast!(nodes[2], true);
2949         check_added_monitors!(nodes[2], 1);
2950         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2951         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2952         assert_eq!(node_txn.len(), 1);
2953         check_spends!(node_txn[0], chan_2.3);
2954         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2955
2956         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2957         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2958         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2959         mine_transaction(&nodes[1], &commitment_tx[0]);
2960         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2961         let timeout_tx;
2962         {
2963                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2964                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2965                 assert_eq!(node_txn[0], node_txn[3]);
2966                 assert_eq!(node_txn[1], node_txn[4]);
2967
2968                 check_spends!(node_txn[2], commitment_tx[0]);
2969                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2970
2971                 check_spends!(node_txn[0], chan_2.3);
2972                 check_spends!(node_txn[1], node_txn[0]);
2973                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2974                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2975
2976                 timeout_tx = node_txn[2].clone();
2977                 node_txn.clear();
2978         }
2979
2980         mine_transaction(&nodes[1], &timeout_tx);
2981         check_added_monitors!(nodes[1], 1);
2982         check_closed_broadcast!(nodes[1], true);
2983         {
2984                 // B will rebroadcast a fee-bumped timeout transaction here.
2985                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2986                 assert_eq!(node_txn.len(), 1);
2987                 check_spends!(node_txn[0], commitment_tx[0]);
2988         }
2989
2990         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2991         {
2992                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2993                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2994                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2995                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2996                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2997                 if node_txn.len() == 1 {
2998                         check_spends!(node_txn[0], chan_2.3);
2999                 } else {
3000                         assert_eq!(node_txn.len(), 0);
3001                 }
3002         }
3003
3004         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 }]);
3005         check_added_monitors!(nodes[1], 1);
3006         let events = nodes[1].node.get_and_clear_pending_msg_events();
3007         assert_eq!(events.len(), 1);
3008         match events[0] {
3009                 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, .. } } => {
3010                         assert!(update_add_htlcs.is_empty());
3011                         assert!(!update_fail_htlcs.is_empty());
3012                         assert!(update_fulfill_htlcs.is_empty());
3013                         assert!(update_fail_malformed_htlcs.is_empty());
3014                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3015                 },
3016                 _ => panic!("Unexpected event"),
3017         };
3018
3019         // Broadcast legit commitment tx from B on A's chain
3020         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3021         check_spends!(commitment_tx[0], chan_1.3);
3022
3023         mine_transaction(&nodes[0], &commitment_tx[0]);
3024         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3025
3026         check_closed_broadcast!(nodes[0], true);
3027         check_added_monitors!(nodes[0], 1);
3028         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3029         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3030         assert_eq!(node_txn.len(), 2);
3031         check_spends!(node_txn[0], chan_1.3);
3032         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3033         check_spends!(node_txn[1], commitment_tx[0]);
3034         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3035 }
3036
3037 #[test]
3038 fn test_htlc_on_chain_timeout() {
3039         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3040         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3041         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3042 }
3043
3044 #[test]
3045 fn test_simple_commitment_revoked_fail_backward() {
3046         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3047         // and fail backward accordingly.
3048
3049         let chanmon_cfgs = create_chanmon_cfgs(3);
3050         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3051         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3052         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3053
3054         // Create some initial channels
3055         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3056         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3057
3058         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3059         // Get the will-be-revoked local txn from nodes[2]
3060         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3061         // Revoke the old state
3062         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3063
3064         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3065
3066         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3067         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3068         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3069         check_added_monitors!(nodes[1], 1);
3070         check_closed_broadcast!(nodes[1], true);
3071
3072         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 }]);
3073         check_added_monitors!(nodes[1], 1);
3074         let events = nodes[1].node.get_and_clear_pending_msg_events();
3075         assert_eq!(events.len(), 1);
3076         match events[0] {
3077                 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, .. } } => {
3078                         assert!(update_add_htlcs.is_empty());
3079                         assert_eq!(update_fail_htlcs.len(), 1);
3080                         assert!(update_fulfill_htlcs.is_empty());
3081                         assert!(update_fail_malformed_htlcs.is_empty());
3082                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3083
3084                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3085                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3086                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3087                 },
3088                 _ => panic!("Unexpected event"),
3089         }
3090 }
3091
3092 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3093         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3094         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3095         // commitment transaction anymore.
3096         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3097         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3098         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3099         // technically disallowed and we should probably handle it reasonably.
3100         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3101         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3102         // transactions:
3103         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3104         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3105         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3106         //   and once they revoke the previous commitment transaction (allowing us to send a new
3107         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3108         let chanmon_cfgs = create_chanmon_cfgs(3);
3109         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3110         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3111         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3112
3113         // Create some initial channels
3114         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3115         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3116
3117         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 });
3118         // Get the will-be-revoked local txn from nodes[2]
3119         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3120         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3121         // Revoke the old state
3122         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3123
3124         let value = if use_dust {
3125                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3126                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3127                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3128         } else { 3000000 };
3129
3130         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3131         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3132         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3133
3134         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3135         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_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         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3145         // Drop the last RAA from 3 -> 2
3146
3147         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3148         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3149         check_added_monitors!(nodes[2], 1);
3150         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3151         assert!(updates.update_add_htlcs.is_empty());
3152         assert!(updates.update_fulfill_htlcs.is_empty());
3153         assert!(updates.update_fail_malformed_htlcs.is_empty());
3154         assert_eq!(updates.update_fail_htlcs.len(), 1);
3155         assert!(updates.update_fee.is_none());
3156         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3157         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3158         check_added_monitors!(nodes[1], 1);
3159         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3160         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3161         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3162         check_added_monitors!(nodes[2], 1);
3163
3164         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3165         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3166         check_added_monitors!(nodes[2], 1);
3167         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3168         assert!(updates.update_add_htlcs.is_empty());
3169         assert!(updates.update_fulfill_htlcs.is_empty());
3170         assert!(updates.update_fail_malformed_htlcs.is_empty());
3171         assert_eq!(updates.update_fail_htlcs.len(), 1);
3172         assert!(updates.update_fee.is_none());
3173         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3174         // At this point first_payment_hash has dropped out of the latest two commitment
3175         // transactions that nodes[1] is tracking...
3176         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3177         check_added_monitors!(nodes[1], 1);
3178         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3179         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3180         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3181         check_added_monitors!(nodes[2], 1);
3182
3183         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3184         // on nodes[2]'s RAA.
3185         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3186         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3187         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3188         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3189         check_added_monitors!(nodes[1], 0);
3190
3191         if deliver_bs_raa {
3192                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3193                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3194                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3195                 check_added_monitors!(nodes[1], 1);
3196                 let events = nodes[1].node.get_and_clear_pending_events();
3197                 assert_eq!(events.len(), 2);
3198                 match events[0] {
3199                         Event::PendingHTLCsForwardable { .. } => { },
3200                         _ => panic!("Unexpected event"),
3201                 };
3202                 match events[1] {
3203                         Event::HTLCHandlingFailed { .. } => { },
3204                         _ => panic!("Unexpected event"),
3205                 }
3206                 // Deliberately don't process the pending fail-back so they all fail back at once after
3207                 // block connection just like the !deliver_bs_raa case
3208         }
3209
3210         let mut failed_htlcs = HashSet::new();
3211         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3212
3213         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3214         check_added_monitors!(nodes[1], 1);
3215         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3216         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3217
3218         let events = nodes[1].node.get_and_clear_pending_events();
3219         assert_eq!(events.len(), if deliver_bs_raa { 2 + (nodes.len() - 1) } else { 4 + nodes.len() });
3220         match events[0] {
3221                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3222                 _ => panic!("Unexepected event"),
3223         }
3224         match events[1] {
3225                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3226                         assert_eq!(*payment_hash, fourth_payment_hash);
3227                 },
3228                 _ => panic!("Unexpected event"),
3229         }
3230         if !deliver_bs_raa {
3231                 match events[2] {
3232                         Event::PaymentFailed { ref payment_hash, .. } => {
3233                                 assert_eq!(*payment_hash, fourth_payment_hash);
3234                         },
3235                         _ => panic!("Unexpected event"),
3236                 }
3237                 match events[3] {
3238                         Event::PendingHTLCsForwardable { .. } => { },
3239                         _ => panic!("Unexpected event"),
3240                 };
3241         }
3242         nodes[1].node.process_pending_htlc_forwards();
3243         check_added_monitors!(nodes[1], 1);
3244
3245         let events = nodes[1].node.get_and_clear_pending_msg_events();
3246         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3247         match events[if deliver_bs_raa { 1 } else { 0 }] {
3248                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3249                 _ => panic!("Unexpected event"),
3250         }
3251         match events[if deliver_bs_raa { 2 } else { 1 }] {
3252                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3253                         assert_eq!(channel_id, chan_2.2);
3254                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3255                 },
3256                 _ => panic!("Unexpected event"),
3257         }
3258         if deliver_bs_raa {
3259                 match events[0] {
3260                         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, .. } } => {
3261                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3262                                 assert_eq!(update_add_htlcs.len(), 1);
3263                                 assert!(update_fulfill_htlcs.is_empty());
3264                                 assert!(update_fail_htlcs.is_empty());
3265                                 assert!(update_fail_malformed_htlcs.is_empty());
3266                         },
3267                         _ => panic!("Unexpected event"),
3268                 }
3269         }
3270         match events[if deliver_bs_raa { 3 } else { 2 }] {
3271                 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, .. } } => {
3272                         assert!(update_add_htlcs.is_empty());
3273                         assert_eq!(update_fail_htlcs.len(), 3);
3274                         assert!(update_fulfill_htlcs.is_empty());
3275                         assert!(update_fail_malformed_htlcs.is_empty());
3276                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3277
3278                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3279                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3280                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3281
3282                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3283
3284                         let events = nodes[0].node.get_and_clear_pending_events();
3285                         assert_eq!(events.len(), 3);
3286                         match events[0] {
3287                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3288                                         assert!(failed_htlcs.insert(payment_hash.0));
3289                                         // If we delivered B's RAA we got an unknown preimage error, not something
3290                                         // that we should update our routing table for.
3291                                         if !deliver_bs_raa {
3292                                                 assert!(network_update.is_some());
3293                                         }
3294                                 },
3295                                 _ => panic!("Unexpected event"),
3296                         }
3297                         match events[1] {
3298                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3299                                         assert!(failed_htlcs.insert(payment_hash.0));
3300                                         assert!(network_update.is_some());
3301                                 },
3302                                 _ => panic!("Unexpected event"),
3303                         }
3304                         match events[2] {
3305                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3306                                         assert!(failed_htlcs.insert(payment_hash.0));
3307                                         assert!(network_update.is_some());
3308                                 },
3309                                 _ => panic!("Unexpected event"),
3310                         }
3311                 },
3312                 _ => panic!("Unexpected event"),
3313         }
3314
3315         assert!(failed_htlcs.contains(&first_payment_hash.0));
3316         assert!(failed_htlcs.contains(&second_payment_hash.0));
3317         assert!(failed_htlcs.contains(&third_payment_hash.0));
3318 }
3319
3320 #[test]
3321 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3322         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3323         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3324         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3325         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3326 }
3327
3328 #[test]
3329 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3330         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3331         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3332         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3333         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3334 }
3335
3336 #[test]
3337 fn fail_backward_pending_htlc_upon_channel_failure() {
3338         let chanmon_cfgs = create_chanmon_cfgs(2);
3339         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3340         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3341         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3342         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3343
3344         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3345         {
3346                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3347                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3348                 check_added_monitors!(nodes[0], 1);
3349
3350                 let payment_event = {
3351                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3352                         assert_eq!(events.len(), 1);
3353                         SendEvent::from_event(events.remove(0))
3354                 };
3355                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3356                 assert_eq!(payment_event.msgs.len(), 1);
3357         }
3358
3359         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3360         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3361         {
3362                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3363                 check_added_monitors!(nodes[0], 0);
3364
3365                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3366         }
3367
3368         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3369         {
3370                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3371
3372                 let secp_ctx = Secp256k1::new();
3373                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3374                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3375                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3376                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3377                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3378
3379                 // Send a 0-msat update_add_htlc to fail the channel.
3380                 let update_add_htlc = msgs::UpdateAddHTLC {
3381                         channel_id: chan.2,
3382                         htlc_id: 0,
3383                         amount_msat: 0,
3384                         payment_hash,
3385                         cltv_expiry,
3386                         onion_routing_packet,
3387                 };
3388                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3389         }
3390         let events = nodes[0].node.get_and_clear_pending_events();
3391         assert_eq!(events.len(), 2);
3392         // Check that Alice fails backward the pending HTLC from the second payment.
3393         match events[0] {
3394                 Event::PaymentPathFailed { payment_hash, .. } => {
3395                         assert_eq!(payment_hash, failed_payment_hash);
3396                 },
3397                 _ => panic!("Unexpected event"),
3398         }
3399         match events[1] {
3400                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3401                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3402                 },
3403                 _ => panic!("Unexpected event {:?}", events[1]),
3404         }
3405         check_closed_broadcast!(nodes[0], true);
3406         check_added_monitors!(nodes[0], 1);
3407 }
3408
3409 #[test]
3410 fn test_htlc_ignore_latest_remote_commitment() {
3411         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3412         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3413         let chanmon_cfgs = create_chanmon_cfgs(2);
3414         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3415         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3416         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3417         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3418
3419         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3420         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3421         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3422         check_closed_broadcast!(nodes[0], true);
3423         check_added_monitors!(nodes[0], 1);
3424         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3425
3426         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3427         assert_eq!(node_txn.len(), 3);
3428         assert_eq!(node_txn[0], node_txn[1]);
3429
3430         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3431         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3432         check_closed_broadcast!(nodes[1], true);
3433         check_added_monitors!(nodes[1], 1);
3434         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3435
3436         // Duplicate the connect_block call since this may happen due to other listeners
3437         // registering new transactions
3438         header.prev_blockhash = header.block_hash();
3439         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3440 }
3441
3442 #[test]
3443 fn test_force_close_fail_back() {
3444         // Check which HTLCs are failed-backwards on channel force-closure
3445         let chanmon_cfgs = create_chanmon_cfgs(3);
3446         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3447         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3448         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3449         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3450         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3451
3452         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3453
3454         let mut payment_event = {
3455                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3456                 check_added_monitors!(nodes[0], 1);
3457
3458                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3459                 assert_eq!(events.len(), 1);
3460                 SendEvent::from_event(events.remove(0))
3461         };
3462
3463         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3464         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3465
3466         expect_pending_htlcs_forwardable!(nodes[1]);
3467
3468         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3469         assert_eq!(events_2.len(), 1);
3470         payment_event = SendEvent::from_event(events_2.remove(0));
3471         assert_eq!(payment_event.msgs.len(), 1);
3472
3473         check_added_monitors!(nodes[1], 1);
3474         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3475         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3476         check_added_monitors!(nodes[2], 1);
3477         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3478
3479         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3480         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3481         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3482
3483         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3484         check_closed_broadcast!(nodes[2], true);
3485         check_added_monitors!(nodes[2], 1);
3486         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3487         let tx = {
3488                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3489                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3490                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3491                 // back to nodes[1] upon timeout otherwise.
3492                 assert_eq!(node_txn.len(), 1);
3493                 node_txn.remove(0)
3494         };
3495
3496         mine_transaction(&nodes[1], &tx);
3497
3498         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3499         check_closed_broadcast!(nodes[1], true);
3500         check_added_monitors!(nodes[1], 1);
3501         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3502
3503         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3504         {
3505                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3506                         .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);
3507         }
3508         mine_transaction(&nodes[2], &tx);
3509         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3510         assert_eq!(node_txn.len(), 1);
3511         assert_eq!(node_txn[0].input.len(), 1);
3512         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3513         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3514         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3515
3516         check_spends!(node_txn[0], tx);
3517 }
3518
3519 #[test]
3520 fn test_dup_events_on_peer_disconnect() {
3521         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3522         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3523         // as we used to generate the event immediately upon receipt of the payment preimage in the
3524         // update_fulfill_htlc message.
3525
3526         let chanmon_cfgs = create_chanmon_cfgs(2);
3527         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3528         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3529         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3530         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3531
3532         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3533
3534         nodes[1].node.claim_funds(payment_preimage);
3535         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3536         check_added_monitors!(nodes[1], 1);
3537         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3538         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3539         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3540
3541         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3542         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3543
3544         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3545         expect_payment_path_successful!(nodes[0]);
3546 }
3547
3548 #[test]
3549 fn test_peer_disconnected_before_funding_broadcasted() {
3550         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3551         // before the funding transaction has been broadcasted.
3552         let chanmon_cfgs = create_chanmon_cfgs(2);
3553         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3554         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3555         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3556
3557         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3558         // broadcasted, even though it's created by `nodes[0]`.
3559         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();
3560         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3561         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3562         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3563         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3564
3565         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3566         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3567
3568         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3569
3570         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3571         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3572
3573         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3574         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3575         // broadcasted.
3576         {
3577                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3578         }
3579
3580         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3581         // disconnected before the funding transaction was broadcasted.
3582         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3583         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3584
3585         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3586         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3587 }
3588
3589 #[test]
3590 fn test_simple_peer_disconnect() {
3591         // Test that we can reconnect when there are no lost messages
3592         let chanmon_cfgs = create_chanmon_cfgs(3);
3593         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3594         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3595         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3596         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3597         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3598
3599         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3600         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3601         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3602
3603         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3604         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3605         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3606         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3607
3608         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3609         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3610         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3611
3612         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3613         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3614         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3615         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3616
3617         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3618         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3619
3620         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3621         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3622
3623         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3624         {
3625                 let events = nodes[0].node.get_and_clear_pending_events();
3626                 assert_eq!(events.len(), 3);
3627                 match events[0] {
3628                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3629                                 assert_eq!(payment_preimage, payment_preimage_3);
3630                                 assert_eq!(payment_hash, payment_hash_3);
3631                         },
3632                         _ => panic!("Unexpected event"),
3633                 }
3634                 match events[1] {
3635                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3636                                 assert_eq!(payment_hash, payment_hash_5);
3637                                 assert!(rejected_by_dest);
3638                         },
3639                         _ => panic!("Unexpected event"),
3640                 }
3641                 match events[2] {
3642                         Event::PaymentPathSuccessful { .. } => {},
3643                         _ => panic!("Unexpected event"),
3644                 }
3645         }
3646
3647         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3648         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3649 }
3650
3651 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3652         // Test that we can reconnect when in-flight HTLC updates get dropped
3653         let chanmon_cfgs = create_chanmon_cfgs(2);
3654         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3655         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3656         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3657
3658         let mut as_channel_ready = None;
3659         if messages_delivered == 0 {
3660                 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3661                 as_channel_ready = Some(channel_ready);
3662                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3663                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3664                 // it before the channel_reestablish message.
3665         } else {
3666                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3667         }
3668
3669         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3670
3671         let payment_event = {
3672                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3673                 check_added_monitors!(nodes[0], 1);
3674
3675                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3676                 assert_eq!(events.len(), 1);
3677                 SendEvent::from_event(events.remove(0))
3678         };
3679         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3680
3681         if messages_delivered < 2 {
3682                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3683         } else {
3684                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3685                 if messages_delivered >= 3 {
3686                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3687                         check_added_monitors!(nodes[1], 1);
3688                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3689
3690                         if messages_delivered >= 4 {
3691                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3692                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3693                                 check_added_monitors!(nodes[0], 1);
3694
3695                                 if messages_delivered >= 5 {
3696                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3697                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3698                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3699                                         check_added_monitors!(nodes[0], 1);
3700
3701                                         if messages_delivered >= 6 {
3702                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3703                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3704                                                 check_added_monitors!(nodes[1], 1);
3705                                         }
3706                                 }
3707                         }
3708                 }
3709         }
3710
3711         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3712         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3713         if messages_delivered < 3 {
3714                 if simulate_broken_lnd {
3715                         // lnd has a long-standing bug where they send a channel_ready prior to a
3716                         // channel_reestablish if you reconnect prior to channel_ready time.
3717                         //
3718                         // Here we simulate that behavior, delivering a channel_ready immediately on
3719                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3720                         // in `reconnect_nodes` but we currently don't fail based on that.
3721                         //
3722                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3723                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3724                 }
3725                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3726                 // received on either side, both sides will need to resend them.
3727                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3728         } else if messages_delivered == 3 {
3729                 // nodes[0] still wants its RAA + commitment_signed
3730                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3731         } else if messages_delivered == 4 {
3732                 // nodes[0] still wants its commitment_signed
3733                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3734         } else if messages_delivered == 5 {
3735                 // nodes[1] still wants its final RAA
3736                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3737         } else if messages_delivered == 6 {
3738                 // Everything was delivered...
3739                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3740         }
3741
3742         let events_1 = nodes[1].node.get_and_clear_pending_events();
3743         assert_eq!(events_1.len(), 1);
3744         match events_1[0] {
3745                 Event::PendingHTLCsForwardable { .. } => { },
3746                 _ => panic!("Unexpected event"),
3747         };
3748
3749         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3750         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3751         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3752
3753         nodes[1].node.process_pending_htlc_forwards();
3754
3755         let events_2 = nodes[1].node.get_and_clear_pending_events();
3756         assert_eq!(events_2.len(), 1);
3757         match events_2[0] {
3758                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3759                         assert_eq!(payment_hash_1, *payment_hash);
3760                         assert_eq!(amount_msat, 1_000_000);
3761                         match &purpose {
3762                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3763                                         assert!(payment_preimage.is_none());
3764                                         assert_eq!(payment_secret_1, *payment_secret);
3765                                 },
3766                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3767                         }
3768                 },
3769                 _ => panic!("Unexpected event"),
3770         }
3771
3772         nodes[1].node.claim_funds(payment_preimage_1);
3773         check_added_monitors!(nodes[1], 1);
3774         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3775
3776         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3777         assert_eq!(events_3.len(), 1);
3778         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3779                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3780                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3781                         assert!(updates.update_add_htlcs.is_empty());
3782                         assert!(updates.update_fail_htlcs.is_empty());
3783                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3784                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3785                         assert!(updates.update_fee.is_none());
3786                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3787                 },
3788                 _ => panic!("Unexpected event"),
3789         };
3790
3791         if messages_delivered >= 1 {
3792                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3793
3794                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3795                 assert_eq!(events_4.len(), 1);
3796                 match events_4[0] {
3797                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3798                                 assert_eq!(payment_preimage_1, *payment_preimage);
3799                                 assert_eq!(payment_hash_1, *payment_hash);
3800                         },
3801                         _ => panic!("Unexpected event"),
3802                 }
3803
3804                 if messages_delivered >= 2 {
3805                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3806                         check_added_monitors!(nodes[0], 1);
3807                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3808
3809                         if messages_delivered >= 3 {
3810                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3811                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3812                                 check_added_monitors!(nodes[1], 1);
3813
3814                                 if messages_delivered >= 4 {
3815                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3816                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3817                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3818                                         check_added_monitors!(nodes[1], 1);
3819
3820                                         if messages_delivered >= 5 {
3821                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3822                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3823                                                 check_added_monitors!(nodes[0], 1);
3824                                         }
3825                                 }
3826                         }
3827                 }
3828         }
3829
3830         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3831         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3832         if messages_delivered < 2 {
3833                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3834                 if messages_delivered < 1 {
3835                         expect_payment_sent!(nodes[0], payment_preimage_1);
3836                 } else {
3837                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3838                 }
3839         } else if messages_delivered == 2 {
3840                 // nodes[0] still wants its RAA + commitment_signed
3841                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3842         } else if messages_delivered == 3 {
3843                 // nodes[0] still wants its commitment_signed
3844                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3845         } else if messages_delivered == 4 {
3846                 // nodes[1] still wants its final RAA
3847                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3848         } else if messages_delivered == 5 {
3849                 // Everything was delivered...
3850                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3851         }
3852
3853         if messages_delivered == 1 || messages_delivered == 2 {
3854                 expect_payment_path_successful!(nodes[0]);
3855         }
3856
3857         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3858         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3859         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3860
3861         if messages_delivered > 2 {
3862                 expect_payment_path_successful!(nodes[0]);
3863         }
3864
3865         // Channel should still work fine...
3866         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3867         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3868         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3869 }
3870
3871 #[test]
3872 fn test_drop_messages_peer_disconnect_a() {
3873         do_test_drop_messages_peer_disconnect(0, true);
3874         do_test_drop_messages_peer_disconnect(0, false);
3875         do_test_drop_messages_peer_disconnect(1, false);
3876         do_test_drop_messages_peer_disconnect(2, false);
3877 }
3878
3879 #[test]
3880 fn test_drop_messages_peer_disconnect_b() {
3881         do_test_drop_messages_peer_disconnect(3, false);
3882         do_test_drop_messages_peer_disconnect(4, false);
3883         do_test_drop_messages_peer_disconnect(5, false);
3884         do_test_drop_messages_peer_disconnect(6, false);
3885 }
3886
3887 #[test]
3888 fn test_funding_peer_disconnect() {
3889         // Test that we can lock in our funding tx while disconnected
3890         let chanmon_cfgs = create_chanmon_cfgs(2);
3891         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3892         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3893         let persister: test_utils::TestPersister;
3894         let new_chain_monitor: test_utils::TestChainMonitor;
3895         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3896         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3897         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3898
3899         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3900         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3901
3902         confirm_transaction(&nodes[0], &tx);
3903         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3904         assert!(events_1.is_empty());
3905
3906         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3907
3908         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3909         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3910
3911         confirm_transaction(&nodes[1], &tx);
3912         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3913         assert!(events_2.is_empty());
3914
3915         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3916         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3917         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3918         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3919
3920         // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3921         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3922         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3923         assert_eq!(events_3.len(), 1);
3924         let as_channel_ready = match events_3[0] {
3925                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3926                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3927                         msg.clone()
3928                 },
3929                 _ => panic!("Unexpected event {:?}", events_3[0]),
3930         };
3931
3932         // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3933         // announcement_signatures as well as channel_update.
3934         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3935         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3936         assert_eq!(events_4.len(), 3);
3937         let chan_id;
3938         let bs_channel_ready = match events_4[0] {
3939                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3940                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3941                         chan_id = msg.channel_id;
3942                         msg.clone()
3943                 },
3944                 _ => panic!("Unexpected event {:?}", events_4[0]),
3945         };
3946         let bs_announcement_sigs = match events_4[1] {
3947                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3948                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3949                         msg.clone()
3950                 },
3951                 _ => panic!("Unexpected event {:?}", events_4[1]),
3952         };
3953         match events_4[2] {
3954                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3955                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3956                 },
3957                 _ => panic!("Unexpected event {:?}", events_4[2]),
3958         }
3959
3960         // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3961         // generates a duplicative private channel_update
3962         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3963         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3964         assert_eq!(events_5.len(), 1);
3965         match events_5[0] {
3966                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3967                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3968                 },
3969                 _ => panic!("Unexpected event {:?}", events_5[0]),
3970         };
3971
3972         // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3973         // announcement_signatures.
3974         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3975         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3976         assert_eq!(events_6.len(), 1);
3977         let as_announcement_sigs = match events_6[0] {
3978                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3979                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3980                         msg.clone()
3981                 },
3982                 _ => panic!("Unexpected event {:?}", events_6[0]),
3983         };
3984
3985         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3986         // broadcast the channel announcement globally, as well as re-send its (now-public)
3987         // channel_update.
3988         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3989         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3990         assert_eq!(events_7.len(), 1);
3991         let (chan_announcement, as_update) = match events_7[0] {
3992                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3993                         (msg.clone(), update_msg.clone())
3994                 },
3995                 _ => panic!("Unexpected event {:?}", events_7[0]),
3996         };
3997
3998         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3999         // same channel_announcement.
4000         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
4001         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
4002         assert_eq!(events_8.len(), 1);
4003         let bs_update = match events_8[0] {
4004                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
4005                         assert_eq!(*msg, chan_announcement);
4006                         update_msg.clone()
4007                 },
4008                 _ => panic!("Unexpected event {:?}", events_8[0]),
4009         };
4010
4011         // Provide the channel announcement and public updates to the network graph
4012         nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
4013         nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
4014         nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
4015
4016         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4017         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4018         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
4019
4020         // Check that after deserialization and reconnection we can still generate an identical
4021         // channel_announcement from the cached signatures.
4022         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4023
4024         let nodes_0_serialized = nodes[0].node.encode();
4025         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4026         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4027
4028         persister = test_utils::TestPersister::new();
4029         let keys_manager = &chanmon_cfgs[0].keys_manager;
4030         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);
4031         nodes[0].chain_monitor = &new_chain_monitor;
4032         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4033         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4034                 &mut chan_0_monitor_read, keys_manager).unwrap();
4035         assert!(chan_0_monitor_read.is_empty());
4036
4037         let mut nodes_0_read = &nodes_0_serialized[..];
4038         let (_, nodes_0_deserialized_tmp) = {
4039                 let mut channel_monitors = HashMap::new();
4040                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4041                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4042                         default_config: UserConfig::default(),
4043                         keys_manager,
4044                         fee_estimator: node_cfgs[0].fee_estimator,
4045                         chain_monitor: nodes[0].chain_monitor,
4046                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4047                         logger: nodes[0].logger,
4048                         channel_monitors,
4049                 }).unwrap()
4050         };
4051         nodes_0_deserialized = nodes_0_deserialized_tmp;
4052         assert!(nodes_0_read.is_empty());
4053
4054         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4055         nodes[0].node = &nodes_0_deserialized;
4056         check_added_monitors!(nodes[0], 1);
4057
4058         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4059
4060         // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4061         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4062         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4063         let mut found_announcement = false;
4064         for event in msgs.iter() {
4065                 match event {
4066                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4067                                 if *msg == chan_announcement { found_announcement = true; }
4068                         },
4069                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4070                         _ => panic!("Unexpected event"),
4071                 }
4072         }
4073         assert!(found_announcement);
4074 }
4075
4076 #[test]
4077 fn test_channel_ready_without_best_block_updated() {
4078         // Previously, if we were offline when a funding transaction was locked in, and then we came
4079         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4080         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4081         // channel_ready immediately instead.
4082         let chanmon_cfgs = create_chanmon_cfgs(2);
4083         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4084         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4085         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4086         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4087
4088         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4089
4090         let conf_height = nodes[0].best_block_info().1 + 1;
4091         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4092         let block_txn = [funding_tx];
4093         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4094         let conf_block_header = nodes[0].get_block_header(conf_height);
4095         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4096
4097         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4098         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4099         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4100 }
4101
4102 #[test]
4103 fn test_drop_messages_peer_disconnect_dual_htlc() {
4104         // Test that we can handle reconnecting when both sides of a channel have pending
4105         // commitment_updates when we disconnect.
4106         let chanmon_cfgs = create_chanmon_cfgs(2);
4107         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4108         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4109         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4110         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4111
4112         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4113
4114         // Now try to send a second payment which will fail to send
4115         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4116         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4117         check_added_monitors!(nodes[0], 1);
4118
4119         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4120         assert_eq!(events_1.len(), 1);
4121         match events_1[0] {
4122                 MessageSendEvent::UpdateHTLCs { .. } => {},
4123                 _ => panic!("Unexpected event"),
4124         }
4125
4126         nodes[1].node.claim_funds(payment_preimage_1);
4127         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4128         check_added_monitors!(nodes[1], 1);
4129
4130         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4131         assert_eq!(events_2.len(), 1);
4132         match events_2[0] {
4133                 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 } } => {
4134                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4135                         assert!(update_add_htlcs.is_empty());
4136                         assert_eq!(update_fulfill_htlcs.len(), 1);
4137                         assert!(update_fail_htlcs.is_empty());
4138                         assert!(update_fail_malformed_htlcs.is_empty());
4139                         assert!(update_fee.is_none());
4140
4141                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4142                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4143                         assert_eq!(events_3.len(), 1);
4144                         match events_3[0] {
4145                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4146                                         assert_eq!(*payment_preimage, payment_preimage_1);
4147                                         assert_eq!(*payment_hash, payment_hash_1);
4148                                 },
4149                                 _ => panic!("Unexpected event"),
4150                         }
4151
4152                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4153                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4154                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4155                         check_added_monitors!(nodes[0], 1);
4156                 },
4157                 _ => panic!("Unexpected event"),
4158         }
4159
4160         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4161         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4162
4163         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4164         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4165         assert_eq!(reestablish_1.len(), 1);
4166         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4167         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4168         assert_eq!(reestablish_2.len(), 1);
4169
4170         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4171         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4172         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4173         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4174
4175         assert!(as_resp.0.is_none());
4176         assert!(bs_resp.0.is_none());
4177
4178         assert!(bs_resp.1.is_none());
4179         assert!(bs_resp.2.is_none());
4180
4181         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4182
4183         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4184         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4185         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4186         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4187         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4188         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4189         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4190         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4191         // No commitment_signed so get_event_msg's assert(len == 1) passes
4192         check_added_monitors!(nodes[1], 1);
4193
4194         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4195         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4196         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4197         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4198         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4199         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4200         assert!(bs_second_commitment_signed.update_fee.is_none());
4201         check_added_monitors!(nodes[1], 1);
4202
4203         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4204         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4205         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4206         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4207         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4208         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4209         assert!(as_commitment_signed.update_fee.is_none());
4210         check_added_monitors!(nodes[0], 1);
4211
4212         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4213         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4214         // No commitment_signed so get_event_msg's assert(len == 1) passes
4215         check_added_monitors!(nodes[0], 1);
4216
4217         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4218         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4219         // No commitment_signed so get_event_msg's assert(len == 1) passes
4220         check_added_monitors!(nodes[1], 1);
4221
4222         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4223         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4224         check_added_monitors!(nodes[1], 1);
4225
4226         expect_pending_htlcs_forwardable!(nodes[1]);
4227
4228         let events_5 = nodes[1].node.get_and_clear_pending_events();
4229         assert_eq!(events_5.len(), 1);
4230         match events_5[0] {
4231                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4232                         assert_eq!(payment_hash_2, *payment_hash);
4233                         match &purpose {
4234                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4235                                         assert!(payment_preimage.is_none());
4236                                         assert_eq!(payment_secret_2, *payment_secret);
4237                                 },
4238                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4239                         }
4240                 },
4241                 _ => panic!("Unexpected event"),
4242         }
4243
4244         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4245         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4246         check_added_monitors!(nodes[0], 1);
4247
4248         expect_payment_path_successful!(nodes[0]);
4249         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4250 }
4251
4252 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4253         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4254         // to avoid our counterparty failing the channel.
4255         let chanmon_cfgs = create_chanmon_cfgs(2);
4256         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4257         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4258         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4259
4260         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4261
4262         let our_payment_hash = if send_partial_mpp {
4263                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4264                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4265                 // indicates there are more HTLCs coming.
4266                 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.
4267                 let payment_id = PaymentId([42; 32]);
4268                 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();
4269                 check_added_monitors!(nodes[0], 1);
4270                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4271                 assert_eq!(events.len(), 1);
4272                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4273                 // hop should *not* yet generate any PaymentReceived event(s).
4274                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4275                 our_payment_hash
4276         } else {
4277                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4278         };
4279
4280         let mut block = Block {
4281                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4282                 txdata: vec![],
4283         };
4284         connect_block(&nodes[0], &block);
4285         connect_block(&nodes[1], &block);
4286         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4287         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4288                 block.header.prev_blockhash = block.block_hash();
4289                 connect_block(&nodes[0], &block);
4290                 connect_block(&nodes[1], &block);
4291         }
4292
4293         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4294
4295         check_added_monitors!(nodes[1], 1);
4296         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4297         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4298         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4299         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4300         assert!(htlc_timeout_updates.update_fee.is_none());
4301
4302         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4303         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4304         // 100_000 msat as u64, followed by the height at which we failed back above
4305         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4306         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4307         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4308 }
4309
4310 #[test]
4311 fn test_htlc_timeout() {
4312         do_test_htlc_timeout(true);
4313         do_test_htlc_timeout(false);
4314 }
4315
4316 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4317         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4318         let chanmon_cfgs = create_chanmon_cfgs(3);
4319         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4320         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4321         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4322         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4323         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4324
4325         // Make sure all nodes are at the same starting height
4326         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4327         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4328         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4329
4330         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4331         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4332         {
4333                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4334         }
4335         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4336         check_added_monitors!(nodes[1], 1);
4337
4338         // Now attempt to route a second payment, which should be placed in the holding cell
4339         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4340         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4341         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4342         if forwarded_htlc {
4343                 check_added_monitors!(nodes[0], 1);
4344                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4345                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4346                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4347                 expect_pending_htlcs_forwardable!(nodes[1]);
4348         }
4349         check_added_monitors!(nodes[1], 0);
4350
4351         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4352         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4353         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4354         connect_blocks(&nodes[1], 1);
4355
4356         if forwarded_htlc {
4357                 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 }]);
4358                 check_added_monitors!(nodes[1], 1);
4359                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4360                 assert_eq!(fail_commit.len(), 1);
4361                 match fail_commit[0] {
4362                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4363                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4364                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4365                         },
4366                         _ => unreachable!(),
4367                 }
4368                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4369         } else {
4370                 let events = nodes[1].node.get_and_clear_pending_events();
4371                 assert_eq!(events.len(), 2);
4372                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4373                         assert_eq!(*payment_hash, second_payment_hash);
4374                 } else { panic!("Unexpected event"); }
4375                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4376                         assert_eq!(*payment_hash, second_payment_hash);
4377                 } else { panic!("Unexpected event"); }
4378         }
4379 }
4380
4381 #[test]
4382 fn test_holding_cell_htlc_add_timeouts() {
4383         do_test_holding_cell_htlc_add_timeouts(false);
4384         do_test_holding_cell_htlc_add_timeouts(true);
4385 }
4386
4387 #[test]
4388 fn test_no_txn_manager_serialize_deserialize() {
4389         let chanmon_cfgs = create_chanmon_cfgs(2);
4390         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4391         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4392         let logger: test_utils::TestLogger;
4393         let fee_estimator: test_utils::TestFeeEstimator;
4394         let persister: test_utils::TestPersister;
4395         let new_chain_monitor: test_utils::TestChainMonitor;
4396         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4397         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4398
4399         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4400
4401         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4402
4403         let nodes_0_serialized = nodes[0].node.encode();
4404         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4405         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4406                 .write(&mut chan_0_monitor_serialized).unwrap();
4407
4408         logger = test_utils::TestLogger::new();
4409         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4410         persister = test_utils::TestPersister::new();
4411         let keys_manager = &chanmon_cfgs[0].keys_manager;
4412         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4413         nodes[0].chain_monitor = &new_chain_monitor;
4414         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4415         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4416                 &mut chan_0_monitor_read, keys_manager).unwrap();
4417         assert!(chan_0_monitor_read.is_empty());
4418
4419         let mut nodes_0_read = &nodes_0_serialized[..];
4420         let config = UserConfig::default();
4421         let (_, nodes_0_deserialized_tmp) = {
4422                 let mut channel_monitors = HashMap::new();
4423                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4424                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4425                         default_config: config,
4426                         keys_manager,
4427                         fee_estimator: &fee_estimator,
4428                         chain_monitor: nodes[0].chain_monitor,
4429                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4430                         logger: &logger,
4431                         channel_monitors,
4432                 }).unwrap()
4433         };
4434         nodes_0_deserialized = nodes_0_deserialized_tmp;
4435         assert!(nodes_0_read.is_empty());
4436
4437         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4438         nodes[0].node = &nodes_0_deserialized;
4439         assert_eq!(nodes[0].node.list_channels().len(), 1);
4440         check_added_monitors!(nodes[0], 1);
4441
4442         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4443         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4444         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4445         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4446
4447         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4448         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4449         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4450         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4451
4452         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4453         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4454         for node in nodes.iter() {
4455                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4456                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4457                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4458         }
4459
4460         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4461 }
4462
4463 #[test]
4464 fn test_manager_serialize_deserialize_events() {
4465         // This test makes sure the events field in ChannelManager survives de/serialization
4466         let chanmon_cfgs = create_chanmon_cfgs(2);
4467         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4468         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4469         let fee_estimator: test_utils::TestFeeEstimator;
4470         let persister: test_utils::TestPersister;
4471         let logger: test_utils::TestLogger;
4472         let new_chain_monitor: test_utils::TestChainMonitor;
4473         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4474         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4475
4476         // Start creating a channel, but stop right before broadcasting the funding transaction
4477         let channel_value = 100000;
4478         let push_msat = 10001;
4479         let a_flags = InitFeatures::known();
4480         let b_flags = InitFeatures::known();
4481         let node_a = nodes.remove(0);
4482         let node_b = nodes.remove(0);
4483         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4484         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()));
4485         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()));
4486
4487         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4488
4489         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4490         check_added_monitors!(node_a, 0);
4491
4492         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()));
4493         {
4494                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4495                 assert_eq!(added_monitors.len(), 1);
4496                 assert_eq!(added_monitors[0].0, funding_output);
4497                 added_monitors.clear();
4498         }
4499
4500         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4501         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4502         {
4503                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4504                 assert_eq!(added_monitors.len(), 1);
4505                 assert_eq!(added_monitors[0].0, funding_output);
4506                 added_monitors.clear();
4507         }
4508         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4509
4510         nodes.push(node_a);
4511         nodes.push(node_b);
4512
4513         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4514         let nodes_0_serialized = nodes[0].node.encode();
4515         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4516         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4517
4518         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4519         logger = test_utils::TestLogger::new();
4520         persister = test_utils::TestPersister::new();
4521         let keys_manager = &chanmon_cfgs[0].keys_manager;
4522         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4523         nodes[0].chain_monitor = &new_chain_monitor;
4524         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4525         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4526                 &mut chan_0_monitor_read, keys_manager).unwrap();
4527         assert!(chan_0_monitor_read.is_empty());
4528
4529         let mut nodes_0_read = &nodes_0_serialized[..];
4530         let config = UserConfig::default();
4531         let (_, nodes_0_deserialized_tmp) = {
4532                 let mut channel_monitors = HashMap::new();
4533                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4534                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4535                         default_config: config,
4536                         keys_manager,
4537                         fee_estimator: &fee_estimator,
4538                         chain_monitor: nodes[0].chain_monitor,
4539                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4540                         logger: &logger,
4541                         channel_monitors,
4542                 }).unwrap()
4543         };
4544         nodes_0_deserialized = nodes_0_deserialized_tmp;
4545         assert!(nodes_0_read.is_empty());
4546
4547         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4548
4549         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4550         nodes[0].node = &nodes_0_deserialized;
4551
4552         // After deserializing, make sure the funding_transaction is still held by the channel manager
4553         let events_4 = nodes[0].node.get_and_clear_pending_events();
4554         assert_eq!(events_4.len(), 0);
4555         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4556         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4557
4558         // Make sure the channel is functioning as though the de/serialization never happened
4559         assert_eq!(nodes[0].node.list_channels().len(), 1);
4560         check_added_monitors!(nodes[0], 1);
4561
4562         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4563         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4564         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4565         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4566
4567         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4568         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4569         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4570         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4571
4572         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4573         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4574         for node in nodes.iter() {
4575                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4576                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4577                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4578         }
4579
4580         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4581 }
4582
4583 #[test]
4584 fn test_simple_manager_serialize_deserialize() {
4585         let chanmon_cfgs = create_chanmon_cfgs(2);
4586         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4587         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4588         let logger: test_utils::TestLogger;
4589         let fee_estimator: test_utils::TestFeeEstimator;
4590         let persister: test_utils::TestPersister;
4591         let new_chain_monitor: test_utils::TestChainMonitor;
4592         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4593         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4594         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4595
4596         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4597         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4598
4599         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4600
4601         let nodes_0_serialized = nodes[0].node.encode();
4602         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4603         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4604
4605         logger = test_utils::TestLogger::new();
4606         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4607         persister = test_utils::TestPersister::new();
4608         let keys_manager = &chanmon_cfgs[0].keys_manager;
4609         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4610         nodes[0].chain_monitor = &new_chain_monitor;
4611         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4612         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4613                 &mut chan_0_monitor_read, keys_manager).unwrap();
4614         assert!(chan_0_monitor_read.is_empty());
4615
4616         let mut nodes_0_read = &nodes_0_serialized[..];
4617         let (_, nodes_0_deserialized_tmp) = {
4618                 let mut channel_monitors = HashMap::new();
4619                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4620                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4621                         default_config: UserConfig::default(),
4622                         keys_manager,
4623                         fee_estimator: &fee_estimator,
4624                         chain_monitor: nodes[0].chain_monitor,
4625                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4626                         logger: &logger,
4627                         channel_monitors,
4628                 }).unwrap()
4629         };
4630         nodes_0_deserialized = nodes_0_deserialized_tmp;
4631         assert!(nodes_0_read.is_empty());
4632
4633         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4634         nodes[0].node = &nodes_0_deserialized;
4635         check_added_monitors!(nodes[0], 1);
4636
4637         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4638
4639         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4640         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4641 }
4642
4643 #[test]
4644 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4645         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4646         let chanmon_cfgs = create_chanmon_cfgs(4);
4647         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4648         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4649         let logger: test_utils::TestLogger;
4650         let fee_estimator: test_utils::TestFeeEstimator;
4651         let persister: test_utils::TestPersister;
4652         let new_chain_monitor: test_utils::TestChainMonitor;
4653         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4654         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4655         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4656         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4657         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4658
4659         let mut node_0_stale_monitors_serialized = Vec::new();
4660         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4661                 let mut writer = test_utils::TestVecWriter(Vec::new());
4662                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4663                 node_0_stale_monitors_serialized.push(writer.0);
4664         }
4665
4666         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4667
4668         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4669         let nodes_0_serialized = nodes[0].node.encode();
4670
4671         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4672         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4673         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4674         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4675
4676         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4677         // nodes[3])
4678         let mut node_0_monitors_serialized = Vec::new();
4679         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4680                 let mut writer = test_utils::TestVecWriter(Vec::new());
4681                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4682                 node_0_monitors_serialized.push(writer.0);
4683         }
4684
4685         logger = test_utils::TestLogger::new();
4686         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4687         persister = test_utils::TestPersister::new();
4688         let keys_manager = &chanmon_cfgs[0].keys_manager;
4689         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4690         nodes[0].chain_monitor = &new_chain_monitor;
4691
4692
4693         let mut node_0_stale_monitors = Vec::new();
4694         for serialized in node_0_stale_monitors_serialized.iter() {
4695                 let mut read = &serialized[..];
4696                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4697                 assert!(read.is_empty());
4698                 node_0_stale_monitors.push(monitor);
4699         }
4700
4701         let mut node_0_monitors = Vec::new();
4702         for serialized in node_0_monitors_serialized.iter() {
4703                 let mut read = &serialized[..];
4704                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4705                 assert!(read.is_empty());
4706                 node_0_monitors.push(monitor);
4707         }
4708
4709         let mut nodes_0_read = &nodes_0_serialized[..];
4710         if let Err(msgs::DecodeError::InvalidValue) =
4711                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4712                 default_config: UserConfig::default(),
4713                 keys_manager,
4714                 fee_estimator: &fee_estimator,
4715                 chain_monitor: nodes[0].chain_monitor,
4716                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4717                 logger: &logger,
4718                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4719         }) { } else {
4720                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4721         };
4722
4723         let mut nodes_0_read = &nodes_0_serialized[..];
4724         let (_, nodes_0_deserialized_tmp) =
4725                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4726                 default_config: UserConfig::default(),
4727                 keys_manager,
4728                 fee_estimator: &fee_estimator,
4729                 chain_monitor: nodes[0].chain_monitor,
4730                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4731                 logger: &logger,
4732                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4733         }).unwrap();
4734         nodes_0_deserialized = nodes_0_deserialized_tmp;
4735         assert!(nodes_0_read.is_empty());
4736
4737         { // Channel close should result in a commitment tx
4738                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4739                 assert_eq!(txn.len(), 1);
4740                 check_spends!(txn[0], funding_tx);
4741                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4742         }
4743
4744         for monitor in node_0_monitors.drain(..) {
4745                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4746                 check_added_monitors!(nodes[0], 1);
4747         }
4748         nodes[0].node = &nodes_0_deserialized;
4749         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4750
4751         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4752         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4753         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4754         //... and we can even still claim the payment!
4755         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4756
4757         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4758         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4759         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4760         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4761         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4762         assert_eq!(msg_events.len(), 1);
4763         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4764                 match action {
4765                         &ErrorAction::SendErrorMessage { ref msg } => {
4766                                 assert_eq!(msg.channel_id, channel_id);
4767                         },
4768                         _ => panic!("Unexpected event!"),
4769                 }
4770         }
4771 }
4772
4773 macro_rules! check_spendable_outputs {
4774         ($node: expr, $keysinterface: expr) => {
4775                 {
4776                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4777                         let mut txn = Vec::new();
4778                         let mut all_outputs = Vec::new();
4779                         let secp_ctx = Secp256k1::new();
4780                         for event in events.drain(..) {
4781                                 match event {
4782                                         Event::SpendableOutputs { mut outputs } => {
4783                                                 for outp in outputs.drain(..) {
4784                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4785                                                         all_outputs.push(outp);
4786                                                 }
4787                                         },
4788                                         _ => panic!("Unexpected event"),
4789                                 };
4790                         }
4791                         if all_outputs.len() > 1 {
4792                                 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) {
4793                                         txn.push(tx);
4794                                 }
4795                         }
4796                         txn
4797                 }
4798         }
4799 }
4800
4801 #[test]
4802 fn test_claim_sizeable_push_msat() {
4803         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4804         let chanmon_cfgs = create_chanmon_cfgs(2);
4805         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4806         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4807         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4808
4809         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4810         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4811         check_closed_broadcast!(nodes[1], true);
4812         check_added_monitors!(nodes[1], 1);
4813         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4814         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4815         assert_eq!(node_txn.len(), 1);
4816         check_spends!(node_txn[0], chan.3);
4817         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
4818
4819         mine_transaction(&nodes[1], &node_txn[0]);
4820         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4821
4822         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4823         assert_eq!(spend_txn.len(), 1);
4824         assert_eq!(spend_txn[0].input.len(), 1);
4825         check_spends!(spend_txn[0], node_txn[0]);
4826         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4827 }
4828
4829 #[test]
4830 fn test_claim_on_remote_sizeable_push_msat() {
4831         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4832         // to_remote output is encumbered by a P2WPKH
4833         let chanmon_cfgs = create_chanmon_cfgs(2);
4834         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4835         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4836         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4837
4838         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4839         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4840         check_closed_broadcast!(nodes[0], true);
4841         check_added_monitors!(nodes[0], 1);
4842         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4843
4844         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4845         assert_eq!(node_txn.len(), 1);
4846         check_spends!(node_txn[0], chan.3);
4847         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
4848
4849         mine_transaction(&nodes[1], &node_txn[0]);
4850         check_closed_broadcast!(nodes[1], true);
4851         check_added_monitors!(nodes[1], 1);
4852         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4853         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4854
4855         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4856         assert_eq!(spend_txn.len(), 1);
4857         check_spends!(spend_txn[0], node_txn[0]);
4858 }
4859
4860 #[test]
4861 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4862         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4863         // to_remote output is encumbered by a P2WPKH
4864
4865         let chanmon_cfgs = create_chanmon_cfgs(2);
4866         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4867         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4868         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4869
4870         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4871         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4872         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4873         assert_eq!(revoked_local_txn[0].input.len(), 1);
4874         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4875
4876         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4877         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4878         check_closed_broadcast!(nodes[1], true);
4879         check_added_monitors!(nodes[1], 1);
4880         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4881
4882         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4883         mine_transaction(&nodes[1], &node_txn[0]);
4884         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4885
4886         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4887         assert_eq!(spend_txn.len(), 3);
4888         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4889         check_spends!(spend_txn[1], node_txn[0]);
4890         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4891 }
4892
4893 #[test]
4894 fn test_static_spendable_outputs_preimage_tx() {
4895         let chanmon_cfgs = create_chanmon_cfgs(2);
4896         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4897         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4898         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4899
4900         // Create some initial channels
4901         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4902
4903         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4904
4905         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4906         assert_eq!(commitment_tx[0].input.len(), 1);
4907         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4908
4909         // Settle A's commitment tx on B's chain
4910         nodes[1].node.claim_funds(payment_preimage);
4911         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4912         check_added_monitors!(nodes[1], 1);
4913         mine_transaction(&nodes[1], &commitment_tx[0]);
4914         check_added_monitors!(nodes[1], 1);
4915         let events = nodes[1].node.get_and_clear_pending_msg_events();
4916         match events[0] {
4917                 MessageSendEvent::UpdateHTLCs { .. } => {},
4918                 _ => panic!("Unexpected event"),
4919         }
4920         match events[1] {
4921                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4922                 _ => panic!("Unexepected event"),
4923         }
4924
4925         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4926         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4927         assert_eq!(node_txn.len(), 3);
4928         check_spends!(node_txn[0], commitment_tx[0]);
4929         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4930         check_spends!(node_txn[1], chan_1.3);
4931         check_spends!(node_txn[2], node_txn[1]);
4932
4933         mine_transaction(&nodes[1], &node_txn[0]);
4934         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4935         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4936
4937         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4938         assert_eq!(spend_txn.len(), 1);
4939         check_spends!(spend_txn[0], node_txn[0]);
4940 }
4941
4942 #[test]
4943 fn test_static_spendable_outputs_timeout_tx() {
4944         let chanmon_cfgs = create_chanmon_cfgs(2);
4945         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4946         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4947         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4948
4949         // Create some initial channels
4950         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4951
4952         // Rebalance the network a bit by relaying one payment through all the channels ...
4953         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4954
4955         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4956
4957         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4958         assert_eq!(commitment_tx[0].input.len(), 1);
4959         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4960
4961         // Settle A's commitment tx on B' chain
4962         mine_transaction(&nodes[1], &commitment_tx[0]);
4963         check_added_monitors!(nodes[1], 1);
4964         let events = nodes[1].node.get_and_clear_pending_msg_events();
4965         match events[0] {
4966                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4967                 _ => panic!("Unexpected event"),
4968         }
4969         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4970
4971         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4972         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4973         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4974         check_spends!(node_txn[0], chan_1.3.clone());
4975         check_spends!(node_txn[1],  commitment_tx[0].clone());
4976         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4977
4978         mine_transaction(&nodes[1], &node_txn[1]);
4979         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4980         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4981         expect_payment_failed!(nodes[1], our_payment_hash, true);
4982
4983         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4984         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4985         check_spends!(spend_txn[0], commitment_tx[0]);
4986         check_spends!(spend_txn[1], node_txn[1]);
4987         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4988 }
4989
4990 #[test]
4991 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4992         let chanmon_cfgs = create_chanmon_cfgs(2);
4993         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4994         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4995         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4996
4997         // Create some initial channels
4998         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4999
5000         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5001         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5002         assert_eq!(revoked_local_txn[0].input.len(), 1);
5003         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5004
5005         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5006
5007         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5008         check_closed_broadcast!(nodes[1], true);
5009         check_added_monitors!(nodes[1], 1);
5010         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5011
5012         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5013         assert_eq!(node_txn.len(), 2);
5014         assert_eq!(node_txn[0].input.len(), 2);
5015         check_spends!(node_txn[0], revoked_local_txn[0]);
5016
5017         mine_transaction(&nodes[1], &node_txn[0]);
5018         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5019
5020         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5021         assert_eq!(spend_txn.len(), 1);
5022         check_spends!(spend_txn[0], node_txn[0]);
5023 }
5024
5025 #[test]
5026 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5027         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5028         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5029         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5030         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5031         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5032
5033         // Create some initial channels
5034         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5035
5036         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5037         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5038         assert_eq!(revoked_local_txn[0].input.len(), 1);
5039         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5040
5041         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5042
5043         // A will generate HTLC-Timeout from revoked commitment tx
5044         mine_transaction(&nodes[0], &revoked_local_txn[0]);
5045         check_closed_broadcast!(nodes[0], true);
5046         check_added_monitors!(nodes[0], 1);
5047         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5048         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5049
5050         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5051         assert_eq!(revoked_htlc_txn.len(), 2);
5052         check_spends!(revoked_htlc_txn[0], chan_1.3);
5053         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5054         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5055         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5056         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5057
5058         // B will generate justice tx from A's revoked commitment/HTLC tx
5059         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5060         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5061         check_closed_broadcast!(nodes[1], true);
5062         check_added_monitors!(nodes[1], 1);
5063         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5064
5065         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5066         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5067         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5068         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5069         // transactions next...
5070         assert_eq!(node_txn[0].input.len(), 3);
5071         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5072
5073         assert_eq!(node_txn[1].input.len(), 2);
5074         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5075         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5076                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5077         } else {
5078                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5079                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5080         }
5081
5082         assert_eq!(node_txn[2].input.len(), 1);
5083         check_spends!(node_txn[2], chan_1.3);
5084
5085         mine_transaction(&nodes[1], &node_txn[1]);
5086         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5087
5088         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5089         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5090         assert_eq!(spend_txn.len(), 1);
5091         assert_eq!(spend_txn[0].input.len(), 1);
5092         check_spends!(spend_txn[0], node_txn[1]);
5093 }
5094
5095 #[test]
5096 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5097         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5098         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5099         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5100         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5101         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5102
5103         // Create some initial channels
5104         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5105
5106         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5107         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5108         assert_eq!(revoked_local_txn[0].input.len(), 1);
5109         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5110
5111         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5112         assert_eq!(revoked_local_txn[0].output.len(), 2);
5113
5114         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5115
5116         // B will generate HTLC-Success from revoked commitment tx
5117         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5118         check_closed_broadcast!(nodes[1], true);
5119         check_added_monitors!(nodes[1], 1);
5120         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5121         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5122
5123         assert_eq!(revoked_htlc_txn.len(), 2);
5124         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5125         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5126         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5127
5128         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5129         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5130         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5131
5132         // A will generate justice tx from B's revoked commitment/HTLC tx
5133         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5134         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5135         check_closed_broadcast!(nodes[0], true);
5136         check_added_monitors!(nodes[0], 1);
5137         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5138
5139         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5140         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5141
5142         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5143         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5144         // transactions next...
5145         assert_eq!(node_txn[0].input.len(), 2);
5146         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5147         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5148                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5149         } else {
5150                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5151                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5152         }
5153
5154         assert_eq!(node_txn[1].input.len(), 1);
5155         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5156
5157         check_spends!(node_txn[2], chan_1.3);
5158
5159         mine_transaction(&nodes[0], &node_txn[1]);
5160         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5161
5162         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5163         // didn't try to generate any new transactions.
5164
5165         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5166         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5167         assert_eq!(spend_txn.len(), 3);
5168         assert_eq!(spend_txn[0].input.len(), 1);
5169         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5170         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5171         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5172         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5173 }
5174
5175 #[test]
5176 fn test_onchain_to_onchain_claim() {
5177         // Test that in case of channel closure, we detect the state of output and claim HTLC
5178         // on downstream peer's remote commitment tx.
5179         // First, have C claim an HTLC against its own latest commitment transaction.
5180         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5181         // channel.
5182         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5183         // gets broadcast.
5184
5185         let chanmon_cfgs = create_chanmon_cfgs(3);
5186         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5187         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5188         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5189
5190         // Create some initial channels
5191         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5192         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5193
5194         // Ensure all nodes are at the same height
5195         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5196         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5197         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5198         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5199
5200         // Rebalance the network a bit by relaying one payment through all the channels ...
5201         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5202         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5203
5204         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5205         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5206         check_spends!(commitment_tx[0], chan_2.3);
5207         nodes[2].node.claim_funds(payment_preimage);
5208         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5209         check_added_monitors!(nodes[2], 1);
5210         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5211         assert!(updates.update_add_htlcs.is_empty());
5212         assert!(updates.update_fail_htlcs.is_empty());
5213         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5214         assert!(updates.update_fail_malformed_htlcs.is_empty());
5215
5216         mine_transaction(&nodes[2], &commitment_tx[0]);
5217         check_closed_broadcast!(nodes[2], true);
5218         check_added_monitors!(nodes[2], 1);
5219         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5220
5221         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5222         assert_eq!(c_txn.len(), 3);
5223         assert_eq!(c_txn[0], c_txn[2]);
5224         assert_eq!(commitment_tx[0], c_txn[1]);
5225         check_spends!(c_txn[1], chan_2.3);
5226         check_spends!(c_txn[2], c_txn[1]);
5227         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5228         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5229         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5230         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5231
5232         // 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
5233         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5234         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5235         check_added_monitors!(nodes[1], 1);
5236         let events = nodes[1].node.get_and_clear_pending_events();
5237         assert_eq!(events.len(), 2);
5238         match events[0] {
5239                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5240                 _ => panic!("Unexpected event"),
5241         }
5242         match events[1] {
5243                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5244                         assert_eq!(fee_earned_msat, Some(1000));
5245                         assert_eq!(prev_channel_id, Some(chan_1.2));
5246                         assert_eq!(claim_from_onchain_tx, true);
5247                         assert_eq!(next_channel_id, Some(chan_2.2));
5248                 },
5249                 _ => panic!("Unexpected event"),
5250         }
5251         {
5252                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5253                 // ChannelMonitor: claim tx
5254                 assert_eq!(b_txn.len(), 1);
5255                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5256                 b_txn.clear();
5257         }
5258         check_added_monitors!(nodes[1], 1);
5259         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5260         assert_eq!(msg_events.len(), 3);
5261         match msg_events[0] {
5262                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5263                 _ => panic!("Unexpected event"),
5264         }
5265         match msg_events[1] {
5266                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5267                 _ => panic!("Unexpected event"),
5268         }
5269         match msg_events[2] {
5270                 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, .. } } => {
5271                         assert!(update_add_htlcs.is_empty());
5272                         assert!(update_fail_htlcs.is_empty());
5273                         assert_eq!(update_fulfill_htlcs.len(), 1);
5274                         assert!(update_fail_malformed_htlcs.is_empty());
5275                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5276                 },
5277                 _ => panic!("Unexpected event"),
5278         };
5279         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5280         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5281         mine_transaction(&nodes[1], &commitment_tx[0]);
5282         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5283         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5284         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5285         assert_eq!(b_txn.len(), 3);
5286         check_spends!(b_txn[1], chan_1.3);
5287         check_spends!(b_txn[2], b_txn[1]);
5288         check_spends!(b_txn[0], commitment_tx[0]);
5289         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5290         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5291         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5292
5293         check_closed_broadcast!(nodes[1], true);
5294         check_added_monitors!(nodes[1], 1);
5295 }
5296
5297 #[test]
5298 fn test_duplicate_payment_hash_one_failure_one_success() {
5299         // Topology : A --> B --> C --> D
5300         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5301         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5302         // we forward one of the payments onwards to D.
5303         let chanmon_cfgs = create_chanmon_cfgs(4);
5304         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5305         // When this test was written, the default base fee floated based on the HTLC count.
5306         // It is now fixed, so we simply set the fee to the expected value here.
5307         let mut config = test_default_channel_config();
5308         config.channel_config.forwarding_fee_base_msat = 196;
5309         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5310                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5311         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5312
5313         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5314         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5315         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5316
5317         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5318         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5319         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5320         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5321         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5322
5323         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5324
5325         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5326         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5327         // script push size limit so that the below script length checks match
5328         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5329         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5330                 .with_features(InvoiceFeatures::known());
5331         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5332         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5333
5334         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5335         assert_eq!(commitment_txn[0].input.len(), 1);
5336         check_spends!(commitment_txn[0], chan_2.3);
5337
5338         mine_transaction(&nodes[1], &commitment_txn[0]);
5339         check_closed_broadcast!(nodes[1], true);
5340         check_added_monitors!(nodes[1], 1);
5341         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5342         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5343
5344         let htlc_timeout_tx;
5345         { // Extract one of the two HTLC-Timeout transaction
5346                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5347                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5348                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5349                 check_spends!(node_txn[0], chan_2.3);
5350
5351                 check_spends!(node_txn[1], commitment_txn[0]);
5352                 assert_eq!(node_txn[1].input.len(), 1);
5353
5354                 if node_txn.len() > 3 {
5355                         check_spends!(node_txn[2], commitment_txn[0]);
5356                         assert_eq!(node_txn[2].input.len(), 1);
5357                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5358
5359                         check_spends!(node_txn[3], commitment_txn[0]);
5360                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5361                 } else {
5362                         check_spends!(node_txn[2], commitment_txn[0]);
5363                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5364                 }
5365
5366                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5367                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5368                 if node_txn.len() > 3 {
5369                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5370                 }
5371                 htlc_timeout_tx = node_txn[1].clone();
5372         }
5373
5374         nodes[2].node.claim_funds(our_payment_preimage);
5375         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5376
5377         mine_transaction(&nodes[2], &commitment_txn[0]);
5378         check_added_monitors!(nodes[2], 2);
5379         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5380         let events = nodes[2].node.get_and_clear_pending_msg_events();
5381         match events[0] {
5382                 MessageSendEvent::UpdateHTLCs { .. } => {},
5383                 _ => panic!("Unexpected event"),
5384         }
5385         match events[1] {
5386                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5387                 _ => panic!("Unexepected event"),
5388         }
5389         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5390         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)
5391         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5392         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5393         assert_eq!(htlc_success_txn[0].input.len(), 1);
5394         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5395         assert_eq!(htlc_success_txn[1].input.len(), 1);
5396         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5397         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5398         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5399         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5400         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5401         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5402
5403         mine_transaction(&nodes[1], &htlc_timeout_tx);
5404         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5405         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 }]);
5406         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5407         assert!(htlc_updates.update_add_htlcs.is_empty());
5408         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5409         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5410         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5411         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5412         check_added_monitors!(nodes[1], 1);
5413
5414         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5415         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5416         {
5417                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5418         }
5419         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5420
5421         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5422         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5423         // and nodes[2] fee) is rounded down and then claimed in full.
5424         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5425         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5426         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5427         assert!(updates.update_add_htlcs.is_empty());
5428         assert!(updates.update_fail_htlcs.is_empty());
5429         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5430         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5431         assert!(updates.update_fail_malformed_htlcs.is_empty());
5432         check_added_monitors!(nodes[1], 1);
5433
5434         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5435         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5436
5437         let events = nodes[0].node.get_and_clear_pending_events();
5438         match events[0] {
5439                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5440                         assert_eq!(*payment_preimage, our_payment_preimage);
5441                         assert_eq!(*payment_hash, duplicate_payment_hash);
5442                 }
5443                 _ => panic!("Unexpected event"),
5444         }
5445 }
5446
5447 #[test]
5448 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5449         let chanmon_cfgs = create_chanmon_cfgs(2);
5450         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5451         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5452         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5453
5454         // Create some initial channels
5455         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5456
5457         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5458         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5459         assert_eq!(local_txn.len(), 1);
5460         assert_eq!(local_txn[0].input.len(), 1);
5461         check_spends!(local_txn[0], chan_1.3);
5462
5463         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5464         nodes[1].node.claim_funds(payment_preimage);
5465         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5466         check_added_monitors!(nodes[1], 1);
5467
5468         mine_transaction(&nodes[1], &local_txn[0]);
5469         check_added_monitors!(nodes[1], 1);
5470         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5471         let events = nodes[1].node.get_and_clear_pending_msg_events();
5472         match events[0] {
5473                 MessageSendEvent::UpdateHTLCs { .. } => {},
5474                 _ => panic!("Unexpected event"),
5475         }
5476         match events[1] {
5477                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5478                 _ => panic!("Unexepected event"),
5479         }
5480         let node_tx = {
5481                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5482                 assert_eq!(node_txn.len(), 3);
5483                 assert_eq!(node_txn[0], node_txn[2]);
5484                 assert_eq!(node_txn[1], local_txn[0]);
5485                 assert_eq!(node_txn[0].input.len(), 1);
5486                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5487                 check_spends!(node_txn[0], local_txn[0]);
5488                 node_txn[0].clone()
5489         };
5490
5491         mine_transaction(&nodes[1], &node_tx);
5492         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5493
5494         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5495         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5496         assert_eq!(spend_txn.len(), 1);
5497         assert_eq!(spend_txn[0].input.len(), 1);
5498         check_spends!(spend_txn[0], node_tx);
5499         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5500 }
5501
5502 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5503         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5504         // unrevoked commitment transaction.
5505         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5506         // a remote RAA before they could be failed backwards (and combinations thereof).
5507         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5508         // use the same payment hashes.
5509         // Thus, we use a six-node network:
5510         //
5511         // A \         / E
5512         //    - C - D -
5513         // B /         \ F
5514         // And test where C fails back to A/B when D announces its latest commitment transaction
5515         let chanmon_cfgs = create_chanmon_cfgs(6);
5516         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5517         // When this test was written, the default base fee floated based on the HTLC count.
5518         // It is now fixed, so we simply set the fee to the expected value here.
5519         let mut config = test_default_channel_config();
5520         config.channel_config.forwarding_fee_base_msat = 196;
5521         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5522                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5523         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5524
5525         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5526         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5527         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5528         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5529         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5530
5531         // Rebalance and check output sanity...
5532         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5533         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5534         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5535
5536         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
5537         // 0th HTLC:
5538         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
5539         // 1st HTLC:
5540         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
5541         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5542         // 2nd HTLC:
5543         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
5544         // 3rd HTLC:
5545         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
5546         // 4th HTLC:
5547         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5548         // 5th HTLC:
5549         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5550         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5551         // 6th HTLC:
5552         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());
5553         // 7th HTLC:
5554         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());
5555
5556         // 8th HTLC:
5557         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5558         // 9th HTLC:
5559         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5560         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
5561
5562         // 10th HTLC:
5563         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
5564         // 11th HTLC:
5565         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5566         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());
5567
5568         // Double-check that six of the new HTLC were added
5569         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5570         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5571         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5572         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5573
5574         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5575         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5576         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5577         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5578         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5579         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5580         check_added_monitors!(nodes[4], 0);
5581
5582         let failed_destinations = vec![
5583                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5584                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5585                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5586                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5587         ];
5588         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5589         check_added_monitors!(nodes[4], 1);
5590
5591         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5592         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5593         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5594         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5595         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5596         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5597
5598         // Fail 3rd below-dust and 7th above-dust HTLCs
5599         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5600         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5601         check_added_monitors!(nodes[5], 0);
5602
5603         let failed_destinations_2 = vec![
5604                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5605                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5606         ];
5607         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5608         check_added_monitors!(nodes[5], 1);
5609
5610         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5611         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5612         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5613         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5614
5615         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5616
5617         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5618         let failed_destinations_3 = vec![
5619                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5620                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5621                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5622                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5623                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5624                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5625         ];
5626         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5627         check_added_monitors!(nodes[3], 1);
5628         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5629         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5630         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5631         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5632         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5633         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5634         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5635         if deliver_last_raa {
5636                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5637         } else {
5638                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5639         }
5640
5641         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5642         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5643         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5644         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5645         //
5646         // We now broadcast the latest commitment transaction, which *should* result in failures for
5647         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5648         // the non-broadcast above-dust HTLCs.
5649         //
5650         // Alternatively, we may broadcast the previous commitment transaction, which should only
5651         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5652         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5653
5654         if announce_latest {
5655                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5656         } else {
5657                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5658         }
5659         let events = nodes[2].node.get_and_clear_pending_events();
5660         let close_event = if deliver_last_raa {
5661                 assert_eq!(events.len(), 2 + 6);
5662                 events.last().clone().unwrap()
5663         } else {
5664                 assert_eq!(events.len(), 1);
5665                 events.last().clone().unwrap()
5666         };
5667         match close_event {
5668                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5669                 _ => panic!("Unexpected event"),
5670         }
5671
5672         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5673         check_closed_broadcast!(nodes[2], true);
5674         if deliver_last_raa {
5675                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5676
5677                 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();
5678                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5679         } else {
5680                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5681                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5682                 } else {
5683                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5684                 };
5685
5686                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5687         }
5688         check_added_monitors!(nodes[2], 3);
5689
5690         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5691         assert_eq!(cs_msgs.len(), 2);
5692         let mut a_done = false;
5693         for msg in cs_msgs {
5694                 match msg {
5695                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5696                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5697                                 // should be failed-backwards here.
5698                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5699                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5700                                         for htlc in &updates.update_fail_htlcs {
5701                                                 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 });
5702                                         }
5703                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5704                                         assert!(!a_done);
5705                                         a_done = true;
5706                                         &nodes[0]
5707                                 } else {
5708                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5709                                         for htlc in &updates.update_fail_htlcs {
5710                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5711                                         }
5712                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5713                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5714                                         &nodes[1]
5715                                 };
5716                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5717                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5718                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5719                                 if announce_latest {
5720                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5721                                         if *node_id == nodes[0].node.get_our_node_id() {
5722                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5723                                         }
5724                                 }
5725                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5726                         },
5727                         _ => panic!("Unexpected event"),
5728                 }
5729         }
5730
5731         let as_events = nodes[0].node.get_and_clear_pending_events();
5732         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5733         let mut as_failds = HashSet::new();
5734         let mut as_updates = 0;
5735         for event in as_events.iter() {
5736                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5737                         assert!(as_failds.insert(*payment_hash));
5738                         if *payment_hash != payment_hash_2 {
5739                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5740                         } else {
5741                                 assert!(!rejected_by_dest);
5742                         }
5743                         if network_update.is_some() {
5744                                 as_updates += 1;
5745                         }
5746                 } else { panic!("Unexpected event"); }
5747         }
5748         assert!(as_failds.contains(&payment_hash_1));
5749         assert!(as_failds.contains(&payment_hash_2));
5750         if announce_latest {
5751                 assert!(as_failds.contains(&payment_hash_3));
5752                 assert!(as_failds.contains(&payment_hash_5));
5753         }
5754         assert!(as_failds.contains(&payment_hash_6));
5755
5756         let bs_events = nodes[1].node.get_and_clear_pending_events();
5757         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5758         let mut bs_failds = HashSet::new();
5759         let mut bs_updates = 0;
5760         for event in bs_events.iter() {
5761                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5762                         assert!(bs_failds.insert(*payment_hash));
5763                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5764                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5765                         } else {
5766                                 assert!(!rejected_by_dest);
5767                         }
5768                         if network_update.is_some() {
5769                                 bs_updates += 1;
5770                         }
5771                 } else { panic!("Unexpected event"); }
5772         }
5773         assert!(bs_failds.contains(&payment_hash_1));
5774         assert!(bs_failds.contains(&payment_hash_2));
5775         if announce_latest {
5776                 assert!(bs_failds.contains(&payment_hash_4));
5777         }
5778         assert!(bs_failds.contains(&payment_hash_5));
5779
5780         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5781         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5782         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5783         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5784         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5785         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5786 }
5787
5788 #[test]
5789 fn test_fail_backwards_latest_remote_announce_a() {
5790         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5791 }
5792
5793 #[test]
5794 fn test_fail_backwards_latest_remote_announce_b() {
5795         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5796 }
5797
5798 #[test]
5799 fn test_fail_backwards_previous_remote_announce() {
5800         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5801         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5802         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5803 }
5804
5805 #[test]
5806 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5807         let chanmon_cfgs = create_chanmon_cfgs(2);
5808         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5809         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5810         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5811
5812         // Create some initial channels
5813         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5814
5815         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5816         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5817         assert_eq!(local_txn[0].input.len(), 1);
5818         check_spends!(local_txn[0], chan_1.3);
5819
5820         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5821         mine_transaction(&nodes[0], &local_txn[0]);
5822         check_closed_broadcast!(nodes[0], true);
5823         check_added_monitors!(nodes[0], 1);
5824         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5825         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5826
5827         let htlc_timeout = {
5828                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5829                 assert_eq!(node_txn.len(), 2);
5830                 check_spends!(node_txn[0], chan_1.3);
5831                 assert_eq!(node_txn[1].input.len(), 1);
5832                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5833                 check_spends!(node_txn[1], local_txn[0]);
5834                 node_txn[1].clone()
5835         };
5836
5837         mine_transaction(&nodes[0], &htlc_timeout);
5838         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5839         expect_payment_failed!(nodes[0], our_payment_hash, true);
5840
5841         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5842         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5843         assert_eq!(spend_txn.len(), 3);
5844         check_spends!(spend_txn[0], local_txn[0]);
5845         assert_eq!(spend_txn[1].input.len(), 1);
5846         check_spends!(spend_txn[1], htlc_timeout);
5847         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5848         assert_eq!(spend_txn[2].input.len(), 2);
5849         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5850         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5851                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5852 }
5853
5854 #[test]
5855 fn test_key_derivation_params() {
5856         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5857         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5858         // let us re-derive the channel key set to then derive a delayed_payment_key.
5859
5860         let chanmon_cfgs = create_chanmon_cfgs(3);
5861
5862         // We manually create the node configuration to backup the seed.
5863         let seed = [42; 32];
5864         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5865         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);
5866         let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5867         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: InitFeatures::known() };
5868         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5869         node_cfgs.remove(0);
5870         node_cfgs.insert(0, node);
5871
5872         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5873         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5874
5875         // Create some initial channels
5876         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5877         // for node 0
5878         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5879         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5880         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5881
5882         // Ensure all nodes are at the same height
5883         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5884         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5885         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5886         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5887
5888         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5889         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5890         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5891         assert_eq!(local_txn_1[0].input.len(), 1);
5892         check_spends!(local_txn_1[0], chan_1.3);
5893
5894         // We check funding pubkey are unique
5895         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]));
5896         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]));
5897         if from_0_funding_key_0 == from_1_funding_key_0
5898             || from_0_funding_key_0 == from_1_funding_key_1
5899             || from_0_funding_key_1 == from_1_funding_key_0
5900             || from_0_funding_key_1 == from_1_funding_key_1 {
5901                 panic!("Funding pubkeys aren't unique");
5902         }
5903
5904         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5905         mine_transaction(&nodes[0], &local_txn_1[0]);
5906         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5907         check_closed_broadcast!(nodes[0], true);
5908         check_added_monitors!(nodes[0], 1);
5909         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5910
5911         let htlc_timeout = {
5912                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5913                 assert_eq!(node_txn[1].input.len(), 1);
5914                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5915                 check_spends!(node_txn[1], local_txn_1[0]);
5916                 node_txn[1].clone()
5917         };
5918
5919         mine_transaction(&nodes[0], &htlc_timeout);
5920         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5921         expect_payment_failed!(nodes[0], our_payment_hash, true);
5922
5923         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5924         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5925         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5926         assert_eq!(spend_txn.len(), 3);
5927         check_spends!(spend_txn[0], local_txn_1[0]);
5928         assert_eq!(spend_txn[1].input.len(), 1);
5929         check_spends!(spend_txn[1], htlc_timeout);
5930         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5931         assert_eq!(spend_txn[2].input.len(), 2);
5932         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5933         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5934                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5935 }
5936
5937 #[test]
5938 fn test_static_output_closing_tx() {
5939         let chanmon_cfgs = create_chanmon_cfgs(2);
5940         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5941         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5942         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5943
5944         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5945
5946         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5947         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5948
5949         mine_transaction(&nodes[0], &closing_tx);
5950         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5951         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5952
5953         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5954         assert_eq!(spend_txn.len(), 1);
5955         check_spends!(spend_txn[0], closing_tx);
5956
5957         mine_transaction(&nodes[1], &closing_tx);
5958         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5959         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5960
5961         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5962         assert_eq!(spend_txn.len(), 1);
5963         check_spends!(spend_txn[0], closing_tx);
5964 }
5965
5966 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5967         let chanmon_cfgs = create_chanmon_cfgs(2);
5968         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5969         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5970         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5971         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5972
5973         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5974
5975         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5976         // present in B's local commitment transaction, but none of A's commitment transactions.
5977         nodes[1].node.claim_funds(payment_preimage);
5978         check_added_monitors!(nodes[1], 1);
5979         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5980
5981         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5982         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5983         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5984
5985         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5986         check_added_monitors!(nodes[0], 1);
5987         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5988         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5989         check_added_monitors!(nodes[1], 1);
5990
5991         let starting_block = nodes[1].best_block_info();
5992         let mut block = Block {
5993                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5994                 txdata: vec![],
5995         };
5996         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5997                 connect_block(&nodes[1], &block);
5998                 block.header.prev_blockhash = block.block_hash();
5999         }
6000         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
6001         check_closed_broadcast!(nodes[1], true);
6002         check_added_monitors!(nodes[1], 1);
6003         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
6004 }
6005
6006 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
6007         let chanmon_cfgs = create_chanmon_cfgs(2);
6008         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6009         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6010         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6011         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6012
6013         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
6014         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
6015         check_added_monitors!(nodes[0], 1);
6016
6017         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6018
6019         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
6020         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
6021         // to "time out" the HTLC.
6022
6023         let starting_block = nodes[1].best_block_info();
6024         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6025
6026         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
6027                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
6028                 header.prev_blockhash = header.block_hash();
6029         }
6030         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6031         check_closed_broadcast!(nodes[0], true);
6032         check_added_monitors!(nodes[0], 1);
6033         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6034 }
6035
6036 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
6037         let chanmon_cfgs = create_chanmon_cfgs(3);
6038         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6039         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6040         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6041         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6042
6043         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6044         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6045         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6046         // actually revoked.
6047         let htlc_value = if use_dust { 50000 } else { 3000000 };
6048         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6049         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6050         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6051         check_added_monitors!(nodes[1], 1);
6052
6053         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6054         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6055         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6056         check_added_monitors!(nodes[0], 1);
6057         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6058         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6059         check_added_monitors!(nodes[1], 1);
6060         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6061         check_added_monitors!(nodes[1], 1);
6062         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6063
6064         if check_revoke_no_close {
6065                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6066                 check_added_monitors!(nodes[0], 1);
6067         }
6068
6069         let starting_block = nodes[1].best_block_info();
6070         let mut block = Block {
6071                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6072                 txdata: vec![],
6073         };
6074         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6075                 connect_block(&nodes[0], &block);
6076                 block.header.prev_blockhash = block.block_hash();
6077         }
6078         if !check_revoke_no_close {
6079                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6080                 check_closed_broadcast!(nodes[0], true);
6081                 check_added_monitors!(nodes[0], 1);
6082                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6083         } else {
6084                 let events = nodes[0].node.get_and_clear_pending_events();
6085                 assert_eq!(events.len(), 2);
6086                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6087                         assert_eq!(*payment_hash, our_payment_hash);
6088                 } else { panic!("Unexpected event"); }
6089                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6090                         assert_eq!(*payment_hash, our_payment_hash);
6091                 } else { panic!("Unexpected event"); }
6092         }
6093 }
6094
6095 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6096 // There are only a few cases to test here:
6097 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
6098 //    broadcastable commitment transactions result in channel closure,
6099 //  * its included in an unrevoked-but-previous remote commitment transaction,
6100 //  * its included in the latest remote or local commitment transactions.
6101 // We test each of the three possible commitment transactions individually and use both dust and
6102 // non-dust HTLCs.
6103 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6104 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6105 // tested for at least one of the cases in other tests.
6106 #[test]
6107 fn htlc_claim_single_commitment_only_a() {
6108         do_htlc_claim_local_commitment_only(true);
6109         do_htlc_claim_local_commitment_only(false);
6110
6111         do_htlc_claim_current_remote_commitment_only(true);
6112         do_htlc_claim_current_remote_commitment_only(false);
6113 }
6114
6115 #[test]
6116 fn htlc_claim_single_commitment_only_b() {
6117         do_htlc_claim_previous_remote_commitment_only(true, false);
6118         do_htlc_claim_previous_remote_commitment_only(false, false);
6119         do_htlc_claim_previous_remote_commitment_only(true, true);
6120         do_htlc_claim_previous_remote_commitment_only(false, true);
6121 }
6122
6123 #[test]
6124 #[should_panic]
6125 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6126         let chanmon_cfgs = create_chanmon_cfgs(2);
6127         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6128         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6129         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6130         // Force duplicate randomness for every get-random call
6131         for node in nodes.iter() {
6132                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6133         }
6134
6135         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6136         let channel_value_satoshis=10000;
6137         let push_msat=10001;
6138         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6139         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6140         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6141         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6142
6143         // Create a second channel with the same random values. This used to panic due to a colliding
6144         // channel_id, but now panics due to a colliding outbound SCID alias.
6145         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6146 }
6147
6148 #[test]
6149 fn bolt2_open_channel_sending_node_checks_part2() {
6150         let chanmon_cfgs = create_chanmon_cfgs(2);
6151         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6152         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6153         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6154
6155         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6156         let channel_value_satoshis=2^24;
6157         let push_msat=10001;
6158         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6159
6160         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6161         let channel_value_satoshis=10000;
6162         // Test when push_msat is equal to 1000 * funding_satoshis.
6163         let push_msat=1000*channel_value_satoshis+1;
6164         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6165
6166         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6167         let channel_value_satoshis=10000;
6168         let push_msat=10001;
6169         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
6170         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6171         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6172
6173         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6174         // 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
6175         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6176
6177         // 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.
6178         assert!(BREAKDOWN_TIMEOUT>0);
6179         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6180
6181         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6182         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6183         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6184
6185         // 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.
6186         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6187         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6188         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6189         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6190         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6191 }
6192
6193 #[test]
6194 fn bolt2_open_channel_sane_dust_limit() {
6195         let chanmon_cfgs = create_chanmon_cfgs(2);
6196         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6197         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6198         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6199
6200         let channel_value_satoshis=1000000;
6201         let push_msat=10001;
6202         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6203         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6204         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6205         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6206
6207         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6208         let events = nodes[1].node.get_and_clear_pending_msg_events();
6209         let err_msg = match events[0] {
6210                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6211                         msg.clone()
6212                 },
6213                 _ => panic!("Unexpected event"),
6214         };
6215         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6216 }
6217
6218 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6219 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6220 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6221 // is no longer affordable once it's freed.
6222 #[test]
6223 fn test_fail_holding_cell_htlc_upon_free() {
6224         let chanmon_cfgs = create_chanmon_cfgs(2);
6225         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6226         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6227         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6228         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6229
6230         // First nodes[0] generates an update_fee, setting the channel's
6231         // pending_update_fee.
6232         {
6233                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6234                 *feerate_lock += 20;
6235         }
6236         nodes[0].node.timer_tick_occurred();
6237         check_added_monitors!(nodes[0], 1);
6238
6239         let events = nodes[0].node.get_and_clear_pending_msg_events();
6240         assert_eq!(events.len(), 1);
6241         let (update_msg, commitment_signed) = match events[0] {
6242                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6243                         (update_fee.as_ref(), commitment_signed)
6244                 },
6245                 _ => panic!("Unexpected event"),
6246         };
6247
6248         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6249
6250         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6251         let channel_reserve = chan_stat.channel_reserve_msat;
6252         let feerate = get_feerate!(nodes[0], chan.2);
6253         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6254
6255         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6256         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6257         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6258
6259         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6260         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6261         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6262         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6263
6264         // Flush the pending fee update.
6265         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6266         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6267         check_added_monitors!(nodes[1], 1);
6268         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6269         check_added_monitors!(nodes[0], 1);
6270
6271         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6272         // HTLC, but now that the fee has been raised the payment will now fail, causing
6273         // us to surface its failure to the user.
6274         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6275         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6276         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);
6277         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 {}",
6278                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6279         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6280
6281         // Check that the payment failed to be sent out.
6282         let events = nodes[0].node.get_and_clear_pending_events();
6283         assert_eq!(events.len(), 1);
6284         match &events[0] {
6285                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, ref short_channel_id, ref error_code, ref error_data, .. } => {
6286                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6287                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6288                         assert_eq!(*rejected_by_dest, false);
6289                         assert_eq!(*all_paths_failed, true);
6290                         assert_eq!(*network_update, None);
6291                         assert_eq!(*short_channel_id, None);
6292                         assert_eq!(*error_code, None);
6293                         assert_eq!(*error_data, None);
6294                 },
6295                 _ => panic!("Unexpected event"),
6296         }
6297 }
6298
6299 // Test that if multiple HTLCs are released from the holding cell and one is
6300 // valid but the other is no longer valid upon release, the valid HTLC can be
6301 // successfully completed while the other one fails as expected.
6302 #[test]
6303 fn test_free_and_fail_holding_cell_htlcs() {
6304         let chanmon_cfgs = create_chanmon_cfgs(2);
6305         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6306         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6307         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6308         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6309
6310         // First nodes[0] generates an update_fee, setting the channel's
6311         // pending_update_fee.
6312         {
6313                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6314                 *feerate_lock += 200;
6315         }
6316         nodes[0].node.timer_tick_occurred();
6317         check_added_monitors!(nodes[0], 1);
6318
6319         let events = nodes[0].node.get_and_clear_pending_msg_events();
6320         assert_eq!(events.len(), 1);
6321         let (update_msg, commitment_signed) = match events[0] {
6322                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6323                         (update_fee.as_ref(), commitment_signed)
6324                 },
6325                 _ => panic!("Unexpected event"),
6326         };
6327
6328         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6329
6330         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6331         let channel_reserve = chan_stat.channel_reserve_msat;
6332         let feerate = get_feerate!(nodes[0], chan.2);
6333         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6334
6335         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6336         let amt_1 = 20000;
6337         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6338         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6339         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6340
6341         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6342         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6343         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6344         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6345         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6346         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6347         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6348
6349         // Flush the pending fee update.
6350         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6351         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6352         check_added_monitors!(nodes[1], 1);
6353         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6354         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6355         check_added_monitors!(nodes[0], 2);
6356
6357         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6358         // but now that the fee has been raised the second payment will now fail, causing us
6359         // to surface its failure to the user. The first payment should succeed.
6360         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6361         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6362         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);
6363         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 {}",
6364                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6365         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6366
6367         // Check that the second payment failed to be sent out.
6368         let events = nodes[0].node.get_and_clear_pending_events();
6369         assert_eq!(events.len(), 1);
6370         match &events[0] {
6371                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, ref short_channel_id, ref error_code, ref error_data, .. } => {
6372                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6373                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6374                         assert_eq!(*rejected_by_dest, false);
6375                         assert_eq!(*all_paths_failed, true);
6376                         assert_eq!(*network_update, None);
6377                         assert_eq!(*short_channel_id, None);
6378                         assert_eq!(*error_code, None);
6379                         assert_eq!(*error_data, None);
6380                 },
6381                 _ => panic!("Unexpected event"),
6382         }
6383
6384         // Complete the first payment and the RAA from the fee update.
6385         let (payment_event, send_raa_event) = {
6386                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6387                 assert_eq!(msgs.len(), 2);
6388                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6389         };
6390         let raa = match send_raa_event {
6391                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6392                 _ => panic!("Unexpected event"),
6393         };
6394         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6395         check_added_monitors!(nodes[1], 1);
6396         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6397         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6398         let events = nodes[1].node.get_and_clear_pending_events();
6399         assert_eq!(events.len(), 1);
6400         match events[0] {
6401                 Event::PendingHTLCsForwardable { .. } => {},
6402                 _ => panic!("Unexpected event"),
6403         }
6404         nodes[1].node.process_pending_htlc_forwards();
6405         let events = nodes[1].node.get_and_clear_pending_events();
6406         assert_eq!(events.len(), 1);
6407         match events[0] {
6408                 Event::PaymentReceived { .. } => {},
6409                 _ => panic!("Unexpected event"),
6410         }
6411         nodes[1].node.claim_funds(payment_preimage_1);
6412         check_added_monitors!(nodes[1], 1);
6413         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6414
6415         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6416         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6417         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6418         expect_payment_sent!(nodes[0], payment_preimage_1);
6419 }
6420
6421 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6422 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6423 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6424 // once it's freed.
6425 #[test]
6426 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6427         let chanmon_cfgs = create_chanmon_cfgs(3);
6428         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6429         // When this test was written, the default base fee floated based on the HTLC count.
6430         // It is now fixed, so we simply set the fee to the expected value here.
6431         let mut config = test_default_channel_config();
6432         config.channel_config.forwarding_fee_base_msat = 196;
6433         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6434         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6435         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6436         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6437
6438         // First nodes[1] generates an update_fee, setting the channel's
6439         // pending_update_fee.
6440         {
6441                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6442                 *feerate_lock += 20;
6443         }
6444         nodes[1].node.timer_tick_occurred();
6445         check_added_monitors!(nodes[1], 1);
6446
6447         let events = nodes[1].node.get_and_clear_pending_msg_events();
6448         assert_eq!(events.len(), 1);
6449         let (update_msg, commitment_signed) = match events[0] {
6450                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6451                         (update_fee.as_ref(), commitment_signed)
6452                 },
6453                 _ => panic!("Unexpected event"),
6454         };
6455
6456         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6457
6458         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6459         let channel_reserve = chan_stat.channel_reserve_msat;
6460         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6461         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6462
6463         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6464         let feemsat = 239;
6465         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6466         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6467         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6468         let payment_event = {
6469                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6470                 check_added_monitors!(nodes[0], 1);
6471
6472                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6473                 assert_eq!(events.len(), 1);
6474
6475                 SendEvent::from_event(events.remove(0))
6476         };
6477         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6478         check_added_monitors!(nodes[1], 0);
6479         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6480         expect_pending_htlcs_forwardable!(nodes[1]);
6481
6482         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6483         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6484
6485         // Flush the pending fee update.
6486         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6487         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6488         check_added_monitors!(nodes[2], 1);
6489         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6490         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6491         check_added_monitors!(nodes[1], 2);
6492
6493         // A final RAA message is generated to finalize the fee update.
6494         let events = nodes[1].node.get_and_clear_pending_msg_events();
6495         assert_eq!(events.len(), 1);
6496
6497         let raa_msg = match &events[0] {
6498                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6499                         msg.clone()
6500                 },
6501                 _ => panic!("Unexpected event"),
6502         };
6503
6504         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6505         check_added_monitors!(nodes[2], 1);
6506         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6507
6508         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6509         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6510         assert_eq!(process_htlc_forwards_event.len(), 2);
6511         match &process_htlc_forwards_event[0] {
6512                 &Event::PendingHTLCsForwardable { .. } => {},
6513                 _ => panic!("Unexpected event"),
6514         }
6515
6516         // In response, we call ChannelManager's process_pending_htlc_forwards
6517         nodes[1].node.process_pending_htlc_forwards();
6518         check_added_monitors!(nodes[1], 1);
6519
6520         // This causes the HTLC to be failed backwards.
6521         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6522         assert_eq!(fail_event.len(), 1);
6523         let (fail_msg, commitment_signed) = match &fail_event[0] {
6524                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6525                         assert_eq!(updates.update_add_htlcs.len(), 0);
6526                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6527                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6528                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6529                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6530                 },
6531                 _ => panic!("Unexpected event"),
6532         };
6533
6534         // Pass the failure messages back to nodes[0].
6535         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6536         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6537
6538         // Complete the HTLC failure+removal process.
6539         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6540         check_added_monitors!(nodes[0], 1);
6541         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6542         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6543         check_added_monitors!(nodes[1], 2);
6544         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6545         assert_eq!(final_raa_event.len(), 1);
6546         let raa = match &final_raa_event[0] {
6547                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6548                 _ => panic!("Unexpected event"),
6549         };
6550         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6551         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6552         check_added_monitors!(nodes[0], 1);
6553 }
6554
6555 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6556 // 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.
6557 //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.
6558
6559 #[test]
6560 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6561         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6562         let chanmon_cfgs = create_chanmon_cfgs(2);
6563         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6564         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6565         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6566         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6567
6568         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6569         route.paths[0][0].fee_msat = 100;
6570
6571         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6572                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6573         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6574         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6575 }
6576
6577 #[test]
6578 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6579         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6580         let chanmon_cfgs = create_chanmon_cfgs(2);
6581         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6582         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6583         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6584         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6585
6586         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6587         route.paths[0][0].fee_msat = 0;
6588         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6589                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6590
6591         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6592         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6593 }
6594
6595 #[test]
6596 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6597         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6598         let chanmon_cfgs = create_chanmon_cfgs(2);
6599         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6600         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6601         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6602         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6603
6604         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6605         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6606         check_added_monitors!(nodes[0], 1);
6607         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6608         updates.update_add_htlcs[0].amount_msat = 0;
6609
6610         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6611         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6612         check_closed_broadcast!(nodes[1], true).unwrap();
6613         check_added_monitors!(nodes[1], 1);
6614         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6615 }
6616
6617 #[test]
6618 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6619         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6620         //It is enforced when constructing a route.
6621         let chanmon_cfgs = create_chanmon_cfgs(2);
6622         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6623         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6624         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6625         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6626
6627         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6628                 .with_features(InvoiceFeatures::known());
6629         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6630         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6631         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6632                 assert_eq!(err, &"Channel CLTV overflowed?"));
6633 }
6634
6635 #[test]
6636 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6637         //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.
6638         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6639         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6640         let chanmon_cfgs = create_chanmon_cfgs(2);
6641         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6642         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6643         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6644         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6645         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6646
6647         for i in 0..max_accepted_htlcs {
6648                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6649                 let payment_event = {
6650                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6651                         check_added_monitors!(nodes[0], 1);
6652
6653                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6654                         assert_eq!(events.len(), 1);
6655                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6656                                 assert_eq!(htlcs[0].htlc_id, i);
6657                         } else {
6658                                 assert!(false);
6659                         }
6660                         SendEvent::from_event(events.remove(0))
6661                 };
6662                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6663                 check_added_monitors!(nodes[1], 0);
6664                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6665
6666                 expect_pending_htlcs_forwardable!(nodes[1]);
6667                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6668         }
6669         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6670         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6671                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6672
6673         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6674         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6675 }
6676
6677 #[test]
6678 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6679         //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.
6680         let chanmon_cfgs = create_chanmon_cfgs(2);
6681         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6682         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6683         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6684         let channel_value = 100000;
6685         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6686         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6687
6688         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6689
6690         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6691         // Manually create a route over our max in flight (which our router normally automatically
6692         // limits us to.
6693         route.paths[0][0].fee_msat =  max_in_flight + 1;
6694         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6695                 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)));
6696
6697         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6698         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);
6699
6700         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6701 }
6702
6703 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6704 #[test]
6705 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6706         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6707         let chanmon_cfgs = create_chanmon_cfgs(2);
6708         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6709         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6710         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6711         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6712         let htlc_minimum_msat: u64;
6713         {
6714                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6715                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6716                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6717         }
6718
6719         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6720         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6721         check_added_monitors!(nodes[0], 1);
6722         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6723         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6724         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6725         assert!(nodes[1].node.list_channels().is_empty());
6726         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6727         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()));
6728         check_added_monitors!(nodes[1], 1);
6729         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6730 }
6731
6732 #[test]
6733 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6734         //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
6735         let chanmon_cfgs = create_chanmon_cfgs(2);
6736         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6737         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6738         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6739         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6740
6741         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6742         let channel_reserve = chan_stat.channel_reserve_msat;
6743         let feerate = get_feerate!(nodes[0], chan.2);
6744         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6745         // The 2* and +1 are for the fee spike reserve.
6746         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6747
6748         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6749         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6750         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6751         check_added_monitors!(nodes[0], 1);
6752         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6753
6754         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6755         // at this time channel-initiatee receivers are not required to enforce that senders
6756         // respect the fee_spike_reserve.
6757         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6758         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6759
6760         assert!(nodes[1].node.list_channels().is_empty());
6761         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6762         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6763         check_added_monitors!(nodes[1], 1);
6764         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6765 }
6766
6767 #[test]
6768 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6769         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6770         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6771         let chanmon_cfgs = create_chanmon_cfgs(2);
6772         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6773         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6774         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6775         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6776
6777         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6778         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6779         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6780         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6781         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6782         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6783
6784         let mut msg = msgs::UpdateAddHTLC {
6785                 channel_id: chan.2,
6786                 htlc_id: 0,
6787                 amount_msat: 1000,
6788                 payment_hash: our_payment_hash,
6789                 cltv_expiry: htlc_cltv,
6790                 onion_routing_packet: onion_packet.clone(),
6791         };
6792
6793         for i in 0..super::channel::OUR_MAX_HTLCS {
6794                 msg.htlc_id = i as u64;
6795                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6796         }
6797         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6798         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6799
6800         assert!(nodes[1].node.list_channels().is_empty());
6801         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6802         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6803         check_added_monitors!(nodes[1], 1);
6804         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6805 }
6806
6807 #[test]
6808 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6809         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6810         let chanmon_cfgs = create_chanmon_cfgs(2);
6811         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6812         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6813         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6814         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6815
6816         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6817         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6818         check_added_monitors!(nodes[0], 1);
6819         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6820         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6821         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6822
6823         assert!(nodes[1].node.list_channels().is_empty());
6824         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6825         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6826         check_added_monitors!(nodes[1], 1);
6827         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6828 }
6829
6830 #[test]
6831 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6832         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6833         let chanmon_cfgs = create_chanmon_cfgs(2);
6834         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6835         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6836         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6837
6838         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6839         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6840         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6841         check_added_monitors!(nodes[0], 1);
6842         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6843         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6844         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6845
6846         assert!(nodes[1].node.list_channels().is_empty());
6847         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6848         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6849         check_added_monitors!(nodes[1], 1);
6850         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6851 }
6852
6853 #[test]
6854 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6855         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6856         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6857         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6858         let chanmon_cfgs = create_chanmon_cfgs(2);
6859         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6860         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6861         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6862
6863         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6864         let (route, our_payment_hash, _, 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         check_added_monitors!(nodes[0], 1);
6867         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6868         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6869
6870         //Disconnect and Reconnect
6871         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6872         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6873         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6874         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6875         assert_eq!(reestablish_1.len(), 1);
6876         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6877         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6878         assert_eq!(reestablish_2.len(), 1);
6879         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6880         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6881         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6882         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6883
6884         //Resend HTLC
6885         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6886         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6887         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6888         check_added_monitors!(nodes[1], 1);
6889         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6890
6891         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6892
6893         assert!(nodes[1].node.list_channels().is_empty());
6894         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6895         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6896         check_added_monitors!(nodes[1], 1);
6897         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6898 }
6899
6900 #[test]
6901 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6902         //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions:     MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6903
6904         let chanmon_cfgs = create_chanmon_cfgs(2);
6905         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6906         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6907         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6908         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6909         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6910         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6911
6912         check_added_monitors!(nodes[0], 1);
6913         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6914         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6915
6916         let update_msg = msgs::UpdateFulfillHTLC{
6917                 channel_id: chan.2,
6918                 htlc_id: 0,
6919                 payment_preimage: our_payment_preimage,
6920         };
6921
6922         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6923
6924         assert!(nodes[0].node.list_channels().is_empty());
6925         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6926         assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6927         check_added_monitors!(nodes[0], 1);
6928         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6929 }
6930
6931 #[test]
6932 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6933         //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.
6934
6935         let chanmon_cfgs = create_chanmon_cfgs(2);
6936         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6937         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6938         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6939         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6940
6941         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6942         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6943         check_added_monitors!(nodes[0], 1);
6944         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6945         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6946
6947         let update_msg = msgs::UpdateFailHTLC{
6948                 channel_id: chan.2,
6949                 htlc_id: 0,
6950                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6951         };
6952
6953         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6954
6955         assert!(nodes[0].node.list_channels().is_empty());
6956         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6957         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()));
6958         check_added_monitors!(nodes[0], 1);
6959         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6960 }
6961
6962 #[test]
6963 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6964         //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.
6965
6966         let chanmon_cfgs = create_chanmon_cfgs(2);
6967         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6968         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6969         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6970         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6971
6972         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6973         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6974         check_added_monitors!(nodes[0], 1);
6975         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6976         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6977         let update_msg = msgs::UpdateFailMalformedHTLC{
6978                 channel_id: chan.2,
6979                 htlc_id: 0,
6980                 sha256_of_onion: [1; 32],
6981                 failure_code: 0x8000,
6982         };
6983
6984         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6985
6986         assert!(nodes[0].node.list_channels().is_empty());
6987         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6988         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()));
6989         check_added_monitors!(nodes[0], 1);
6990         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6991 }
6992
6993 #[test]
6994 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6995         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6996
6997         let chanmon_cfgs = create_chanmon_cfgs(2);
6998         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6999         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7000         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7001         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7002
7003         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
7004
7005         nodes[1].node.claim_funds(our_payment_preimage);
7006         check_added_monitors!(nodes[1], 1);
7007         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7008
7009         let events = nodes[1].node.get_and_clear_pending_msg_events();
7010         assert_eq!(events.len(), 1);
7011         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7012                 match events[0] {
7013                         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, .. } } => {
7014                                 assert!(update_add_htlcs.is_empty());
7015                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7016                                 assert!(update_fail_htlcs.is_empty());
7017                                 assert!(update_fail_malformed_htlcs.is_empty());
7018                                 assert!(update_fee.is_none());
7019                                 update_fulfill_htlcs[0].clone()
7020                         },
7021                         _ => panic!("Unexpected event"),
7022                 }
7023         };
7024
7025         update_fulfill_msg.htlc_id = 1;
7026
7027         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7028
7029         assert!(nodes[0].node.list_channels().is_empty());
7030         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7031         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
7032         check_added_monitors!(nodes[0], 1);
7033         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7034 }
7035
7036 #[test]
7037 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
7038         //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.
7039
7040         let chanmon_cfgs = create_chanmon_cfgs(2);
7041         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7042         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7043         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7044         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7045
7046         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
7047
7048         nodes[1].node.claim_funds(our_payment_preimage);
7049         check_added_monitors!(nodes[1], 1);
7050         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7051
7052         let events = nodes[1].node.get_and_clear_pending_msg_events();
7053         assert_eq!(events.len(), 1);
7054         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7055                 match events[0] {
7056                         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, .. } } => {
7057                                 assert!(update_add_htlcs.is_empty());
7058                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7059                                 assert!(update_fail_htlcs.is_empty());
7060                                 assert!(update_fail_malformed_htlcs.is_empty());
7061                                 assert!(update_fee.is_none());
7062                                 update_fulfill_htlcs[0].clone()
7063                         },
7064                         _ => panic!("Unexpected event"),
7065                 }
7066         };
7067
7068         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7069
7070         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7071
7072         assert!(nodes[0].node.list_channels().is_empty());
7073         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7074         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7075         check_added_monitors!(nodes[0], 1);
7076         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7077 }
7078
7079 #[test]
7080 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7081         //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.
7082
7083         let chanmon_cfgs = create_chanmon_cfgs(2);
7084         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7085         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7086         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7087         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7088
7089         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7090         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7091         check_added_monitors!(nodes[0], 1);
7092
7093         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7094         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7095
7096         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7097         check_added_monitors!(nodes[1], 0);
7098         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7099
7100         let events = nodes[1].node.get_and_clear_pending_msg_events();
7101
7102         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7103                 match events[0] {
7104                         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, .. } } => {
7105                                 assert!(update_add_htlcs.is_empty());
7106                                 assert!(update_fulfill_htlcs.is_empty());
7107                                 assert!(update_fail_htlcs.is_empty());
7108                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7109                                 assert!(update_fee.is_none());
7110                                 update_fail_malformed_htlcs[0].clone()
7111                         },
7112                         _ => panic!("Unexpected event"),
7113                 }
7114         };
7115         update_msg.failure_code &= !0x8000;
7116         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7117
7118         assert!(nodes[0].node.list_channels().is_empty());
7119         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7120         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7121         check_added_monitors!(nodes[0], 1);
7122         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7123 }
7124
7125 #[test]
7126 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7127         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7128         //    * 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.
7129
7130         let chanmon_cfgs = create_chanmon_cfgs(3);
7131         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7132         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7133         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7134         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7135         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7136
7137         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7138
7139         //First hop
7140         let mut payment_event = {
7141                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7142                 check_added_monitors!(nodes[0], 1);
7143                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7144                 assert_eq!(events.len(), 1);
7145                 SendEvent::from_event(events.remove(0))
7146         };
7147         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7148         check_added_monitors!(nodes[1], 0);
7149         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7150         expect_pending_htlcs_forwardable!(nodes[1]);
7151         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7152         assert_eq!(events_2.len(), 1);
7153         check_added_monitors!(nodes[1], 1);
7154         payment_event = SendEvent::from_event(events_2.remove(0));
7155         assert_eq!(payment_event.msgs.len(), 1);
7156
7157         //Second Hop
7158         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7159         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7160         check_added_monitors!(nodes[2], 0);
7161         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7162
7163         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7164         assert_eq!(events_3.len(), 1);
7165         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7166                 match events_3[0] {
7167                         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 } } => {
7168                                 assert!(update_add_htlcs.is_empty());
7169                                 assert!(update_fulfill_htlcs.is_empty());
7170                                 assert!(update_fail_htlcs.is_empty());
7171                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7172                                 assert!(update_fee.is_none());
7173                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7174                         },
7175                         _ => panic!("Unexpected event"),
7176                 }
7177         };
7178
7179         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7180
7181         check_added_monitors!(nodes[1], 0);
7182         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7183         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 }]);
7184         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7185         assert_eq!(events_4.len(), 1);
7186
7187         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7188         match events_4[0] {
7189                 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, .. } } => {
7190                         assert!(update_add_htlcs.is_empty());
7191                         assert!(update_fulfill_htlcs.is_empty());
7192                         assert_eq!(update_fail_htlcs.len(), 1);
7193                         assert!(update_fail_malformed_htlcs.is_empty());
7194                         assert!(update_fee.is_none());
7195                 },
7196                 _ => panic!("Unexpected event"),
7197         };
7198
7199         check_added_monitors!(nodes[1], 1);
7200 }
7201
7202 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7203         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7204         // 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
7205         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7206
7207         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7208         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7209         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7210         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7211         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7212         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7213
7214         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7215
7216         // We route 2 dust-HTLCs between A and B
7217         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7218         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7219         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7220
7221         // Cache one local commitment tx as previous
7222         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7223
7224         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7225         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7226         check_added_monitors!(nodes[1], 0);
7227         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7228         check_added_monitors!(nodes[1], 1);
7229
7230         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7231         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7232         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7233         check_added_monitors!(nodes[0], 1);
7234
7235         // Cache one local commitment tx as lastest
7236         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7237
7238         let events = nodes[0].node.get_and_clear_pending_msg_events();
7239         match events[0] {
7240                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7241                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7242                 },
7243                 _ => panic!("Unexpected event"),
7244         }
7245         match events[1] {
7246                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7247                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7248                 },
7249                 _ => panic!("Unexpected event"),
7250         }
7251
7252         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7253         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7254         if announce_latest {
7255                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7256         } else {
7257                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7258         }
7259
7260         check_closed_broadcast!(nodes[0], true);
7261         check_added_monitors!(nodes[0], 1);
7262         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7263
7264         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7265         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7266         let events = nodes[0].node.get_and_clear_pending_events();
7267         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7268         assert_eq!(events.len(), 2);
7269         let mut first_failed = false;
7270         for event in events {
7271                 match event {
7272                         Event::PaymentPathFailed { payment_hash, .. } => {
7273                                 if payment_hash == payment_hash_1 {
7274                                         assert!(!first_failed);
7275                                         first_failed = true;
7276                                 } else {
7277                                         assert_eq!(payment_hash, payment_hash_2);
7278                                 }
7279                         }
7280                         _ => panic!("Unexpected event"),
7281                 }
7282         }
7283 }
7284
7285 #[test]
7286 fn test_failure_delay_dust_htlc_local_commitment() {
7287         do_test_failure_delay_dust_htlc_local_commitment(true);
7288         do_test_failure_delay_dust_htlc_local_commitment(false);
7289 }
7290
7291 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7292         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7293         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7294         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7295         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7296         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7297         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7298
7299         let chanmon_cfgs = create_chanmon_cfgs(3);
7300         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7301         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7302         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7303         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7304
7305         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7306
7307         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7308         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7309
7310         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7311         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7312
7313         // We revoked bs_commitment_tx
7314         if revoked {
7315                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7316                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7317         }
7318
7319         let mut timeout_tx = Vec::new();
7320         if local {
7321                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7322                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7323                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7324                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7325                 expect_payment_failed!(nodes[0], dust_hash, true);
7326
7327                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7328                 check_closed_broadcast!(nodes[0], true);
7329                 check_added_monitors!(nodes[0], 1);
7330                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7331                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7332                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7333                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7334                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7335                 mine_transaction(&nodes[0], &timeout_tx[0]);
7336                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7337                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7338         } else {
7339                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7340                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7341                 check_closed_broadcast!(nodes[0], true);
7342                 check_added_monitors!(nodes[0], 1);
7343                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7344                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7345
7346                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7347                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7348                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7349                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7350                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7351                 // dust HTLC should have been failed.
7352                 expect_payment_failed!(nodes[0], dust_hash, true);
7353
7354                 if !revoked {
7355                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7356                 } else {
7357                         assert_eq!(timeout_tx[0].lock_time, 0);
7358                 }
7359                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7360                 mine_transaction(&nodes[0], &timeout_tx[0]);
7361                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7362                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7363                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7364         }
7365 }
7366
7367 #[test]
7368 fn test_sweep_outbound_htlc_failure_update() {
7369         do_test_sweep_outbound_htlc_failure_update(false, true);
7370         do_test_sweep_outbound_htlc_failure_update(false, false);
7371         do_test_sweep_outbound_htlc_failure_update(true, false);
7372 }
7373
7374 #[test]
7375 fn test_user_configurable_csv_delay() {
7376         // We test our channel constructors yield errors when we pass them absurd csv delay
7377
7378         let mut low_our_to_self_config = UserConfig::default();
7379         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7380         let mut high_their_to_self_config = UserConfig::default();
7381         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7382         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7383         let chanmon_cfgs = create_chanmon_cfgs(2);
7384         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7385         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7386         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7387
7388         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7389         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7390                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7391                 &low_our_to_self_config, 0, 42)
7392         {
7393                 match error {
7394                         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())); },
7395                         _ => panic!("Unexpected event"),
7396                 }
7397         } else { assert!(false) }
7398
7399         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7400         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7401         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7402         open_channel.to_self_delay = 200;
7403         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7404                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7405                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7406         {
7407                 match error {
7408                         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()));  },
7409                         _ => panic!("Unexpected event"),
7410                 }
7411         } else { assert!(false); }
7412
7413         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7414         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7415         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
7416         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7417         accept_channel.to_self_delay = 200;
7418         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7419         let reason_msg;
7420         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7421                 match action {
7422                         &ErrorAction::SendErrorMessage { ref msg } => {
7423                                 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()));
7424                                 reason_msg = msg.data.clone();
7425                         },
7426                         _ => { panic!(); }
7427                 }
7428         } else { panic!(); }
7429         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7430
7431         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7432         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7433         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7434         open_channel.to_self_delay = 200;
7435         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7436                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7437                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7438         {
7439                 match error {
7440                         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())); },
7441                         _ => panic!("Unexpected event"),
7442                 }
7443         } else { assert!(false); }
7444 }
7445
7446 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7447         // When we get a data_loss_protect proving we're behind, we immediately panic as the
7448         // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7449         // panic message informs the user they should force-close without broadcasting, which is tested
7450         // if `reconnect_panicing` is not set.
7451         let persister;
7452         let logger;
7453         let fee_estimator;
7454         let tx_broadcaster;
7455         let chain_source;
7456         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7457         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7458         // during signing due to revoked tx
7459         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7460         let keys_manager = &chanmon_cfgs[0].keys_manager;
7461         let monitor;
7462         let node_state_0;
7463         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7464         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7465         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7466
7467         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7468
7469         // Cache node A state before any channel update
7470         let previous_node_state = nodes[0].node.encode();
7471         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7472         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7473
7474         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7475         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7476
7477         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7478         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7479
7480         // Restore node A from previous state
7481         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7482         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7483         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7484         tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7485         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7486         persister = test_utils::TestPersister::new();
7487         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7488         node_state_0 = {
7489                 let mut channel_monitors = HashMap::new();
7490                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7491                 <(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 {
7492                         keys_manager: keys_manager,
7493                         fee_estimator: &fee_estimator,
7494                         chain_monitor: &monitor,
7495                         logger: &logger,
7496                         tx_broadcaster: &tx_broadcaster,
7497                         default_config: UserConfig::default(),
7498                         channel_monitors,
7499                 }).unwrap().1
7500         };
7501         nodes[0].node = &node_state_0;
7502         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7503         nodes[0].chain_monitor = &monitor;
7504         nodes[0].chain_source = &chain_source;
7505
7506         check_added_monitors!(nodes[0], 1);
7507
7508         if reconnect_panicing {
7509                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7510                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7511
7512                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7513
7514                 // Check we close channel detecting A is fallen-behind
7515                 // Check that we sent the warning message when we detected that A has fallen behind,
7516                 // and give the possibility for A to recover from the warning.
7517                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7518                 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7519                 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7520
7521                 {
7522                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7523                         // The node B should not broadcast the transaction to force close the channel!
7524                         assert!(node_txn.is_empty());
7525                 }
7526
7527                 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7528                 // Check A panics upon seeing proof it has fallen behind.
7529                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7530                 return; // By this point we should have panic'ed!
7531         }
7532
7533         nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7534         check_added_monitors!(nodes[0], 1);
7535         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7536         {
7537                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7538                 assert_eq!(node_txn.len(), 0);
7539         }
7540
7541         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7542                 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7543                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7544                         match action {
7545                                 &ErrorAction::SendErrorMessage { ref msg } => {
7546                                         assert_eq!(msg.data, "Channel force-closed");
7547                                 },
7548                                 _ => panic!("Unexpected event!"),
7549                         }
7550                 } else {
7551                         panic!("Unexpected event {:?}", msg)
7552                 }
7553         }
7554
7555         // after the warning message sent by B, we should not able to
7556         // use the channel, or reconnect with success to the channel.
7557         assert!(nodes[0].node.list_usable_channels().is_empty());
7558         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7559         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7560         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7561
7562         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7563         let mut err_msgs_0 = Vec::with_capacity(1);
7564         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7565                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7566                         match action {
7567                                 &ErrorAction::SendErrorMessage { ref msg } => {
7568                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7569                                         err_msgs_0.push(msg.clone());
7570                                 },
7571                                 _ => panic!("Unexpected event!"),
7572                         }
7573                 } else {
7574                         panic!("Unexpected event!");
7575                 }
7576         }
7577         assert_eq!(err_msgs_0.len(), 1);
7578         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7579         assert!(nodes[1].node.list_usable_channels().is_empty());
7580         check_added_monitors!(nodes[1], 1);
7581         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7582         check_closed_broadcast!(nodes[1], false);
7583 }
7584
7585 #[test]
7586 #[should_panic]
7587 fn test_data_loss_protect_showing_stale_state_panics() {
7588         do_test_data_loss_protect(true);
7589 }
7590
7591 #[test]
7592 fn test_force_close_without_broadcast() {
7593         do_test_data_loss_protect(false);
7594 }
7595
7596 #[test]
7597 fn test_check_htlc_underpaying() {
7598         // Send payment through A -> B but A is maliciously
7599         // sending a probe payment (i.e less than expected value0
7600         // to B, B should refuse payment.
7601
7602         let chanmon_cfgs = create_chanmon_cfgs(2);
7603         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7604         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7605         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7606
7607         // Create some initial channels
7608         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7609
7610         let scorer = test_utils::TestScorer::with_penalty(0);
7611         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7612         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7613         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();
7614         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7615         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7616         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7617         check_added_monitors!(nodes[0], 1);
7618
7619         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7620         assert_eq!(events.len(), 1);
7621         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7622         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7623         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7624
7625         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7626         // and then will wait a second random delay before failing the HTLC back:
7627         expect_pending_htlcs_forwardable!(nodes[1]);
7628         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7629
7630         // Node 3 is expecting payment of 100_000 but received 10_000,
7631         // it should fail htlc like we didn't know the preimage.
7632         nodes[1].node.process_pending_htlc_forwards();
7633
7634         let events = nodes[1].node.get_and_clear_pending_msg_events();
7635         assert_eq!(events.len(), 1);
7636         let (update_fail_htlc, commitment_signed) = match events[0] {
7637                 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 } } => {
7638                         assert!(update_add_htlcs.is_empty());
7639                         assert!(update_fulfill_htlcs.is_empty());
7640                         assert_eq!(update_fail_htlcs.len(), 1);
7641                         assert!(update_fail_malformed_htlcs.is_empty());
7642                         assert!(update_fee.is_none());
7643                         (update_fail_htlcs[0].clone(), commitment_signed)
7644                 },
7645                 _ => panic!("Unexpected event"),
7646         };
7647         check_added_monitors!(nodes[1], 1);
7648
7649         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7650         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7651
7652         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7653         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7654         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7655         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7656 }
7657
7658 #[test]
7659 fn test_announce_disable_channels() {
7660         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7661         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7662
7663         let chanmon_cfgs = create_chanmon_cfgs(2);
7664         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7665         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7666         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7667
7668         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7669         create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7670         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7671
7672         // Disconnect peers
7673         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7674         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7675
7676         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7677         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7678         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7679         assert_eq!(msg_events.len(), 3);
7680         let mut chans_disabled = HashMap::new();
7681         for e in msg_events {
7682                 match e {
7683                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7684                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7685                                 // Check that each channel gets updated exactly once
7686                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7687                                         panic!("Generated ChannelUpdate for wrong chan!");
7688                                 }
7689                         },
7690                         _ => panic!("Unexpected event"),
7691                 }
7692         }
7693         // Reconnect peers
7694         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7695         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7696         assert_eq!(reestablish_1.len(), 3);
7697         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7698         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7699         assert_eq!(reestablish_2.len(), 3);
7700
7701         // Reestablish chan_1
7702         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7703         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7704         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7705         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7706         // Reestablish chan_2
7707         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7708         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7709         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7710         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7711         // Reestablish chan_3
7712         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7713         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7714         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7715         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7716
7717         nodes[0].node.timer_tick_occurred();
7718         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7719         nodes[0].node.timer_tick_occurred();
7720         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7721         assert_eq!(msg_events.len(), 3);
7722         for e in msg_events {
7723                 match e {
7724                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7725                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7726                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7727                                         // Each update should have a higher timestamp than the previous one, replacing
7728                                         // the old one.
7729                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7730                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7731                                 }
7732                         },
7733                         _ => panic!("Unexpected event"),
7734                 }
7735         }
7736         // Check that each channel gets updated exactly once
7737         assert!(chans_disabled.is_empty());
7738 }
7739
7740 #[test]
7741 fn test_bump_penalty_txn_on_revoked_commitment() {
7742         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7743         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7744
7745         let chanmon_cfgs = create_chanmon_cfgs(2);
7746         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7747         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7748         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7749
7750         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7751
7752         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7753         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7754                 .with_features(InvoiceFeatures::known());
7755         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7756         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7757
7758         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7759         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7760         assert_eq!(revoked_txn[0].output.len(), 4);
7761         assert_eq!(revoked_txn[0].input.len(), 1);
7762         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7763         let revoked_txid = revoked_txn[0].txid();
7764
7765         let mut penalty_sum = 0;
7766         for outp in revoked_txn[0].output.iter() {
7767                 if outp.script_pubkey.is_v0_p2wsh() {
7768                         penalty_sum += outp.value;
7769                 }
7770         }
7771
7772         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7773         let header_114 = connect_blocks(&nodes[1], 14);
7774
7775         // Actually revoke tx by claiming a HTLC
7776         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7777         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7778         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7779         check_added_monitors!(nodes[1], 1);
7780
7781         // One or more justice tx should have been broadcast, check it
7782         let penalty_1;
7783         let feerate_1;
7784         {
7785                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7786                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7787                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7788                 assert_eq!(node_txn[0].output.len(), 1);
7789                 check_spends!(node_txn[0], revoked_txn[0]);
7790                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7791                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7792                 penalty_1 = node_txn[0].txid();
7793                 node_txn.clear();
7794         };
7795
7796         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7797         connect_blocks(&nodes[1], 15);
7798         let mut penalty_2 = penalty_1;
7799         let mut feerate_2 = 0;
7800         {
7801                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7802                 assert_eq!(node_txn.len(), 1);
7803                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7804                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7805                         assert_eq!(node_txn[0].output.len(), 1);
7806                         check_spends!(node_txn[0], revoked_txn[0]);
7807                         penalty_2 = node_txn[0].txid();
7808                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7809                         assert_ne!(penalty_2, penalty_1);
7810                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7811                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7812                         // Verify 25% bump heuristic
7813                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7814                         node_txn.clear();
7815                 }
7816         }
7817         assert_ne!(feerate_2, 0);
7818
7819         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7820         connect_blocks(&nodes[1], 1);
7821         let penalty_3;
7822         let mut feerate_3 = 0;
7823         {
7824                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7825                 assert_eq!(node_txn.len(), 1);
7826                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7827                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7828                         assert_eq!(node_txn[0].output.len(), 1);
7829                         check_spends!(node_txn[0], revoked_txn[0]);
7830                         penalty_3 = node_txn[0].txid();
7831                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7832                         assert_ne!(penalty_3, penalty_2);
7833                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7834                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7835                         // Verify 25% bump heuristic
7836                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7837                         node_txn.clear();
7838                 }
7839         }
7840         assert_ne!(feerate_3, 0);
7841
7842         nodes[1].node.get_and_clear_pending_events();
7843         nodes[1].node.get_and_clear_pending_msg_events();
7844 }
7845
7846 #[test]
7847 fn test_bump_penalty_txn_on_revoked_htlcs() {
7848         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7849         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7850
7851         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7852         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7853         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7854         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7855         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7856
7857         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7858         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7859         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7860         let scorer = test_utils::TestScorer::with_penalty(0);
7861         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7862         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7863                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7864         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7865         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7866         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7867                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7868         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7869
7870         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7871         assert_eq!(revoked_local_txn[0].input.len(), 1);
7872         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7873
7874         // Revoke local commitment tx
7875         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7876
7877         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7878         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7879         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7880         check_closed_broadcast!(nodes[1], true);
7881         check_added_monitors!(nodes[1], 1);
7882         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7883         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7884
7885         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7886         assert_eq!(revoked_htlc_txn.len(), 3);
7887         check_spends!(revoked_htlc_txn[1], chan.3);
7888
7889         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7890         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7891         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7892
7893         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7894         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7895         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7896         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7897
7898         // Broadcast set of revoked txn on A
7899         let hash_128 = connect_blocks(&nodes[0], 40);
7900         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7901         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7902         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7903         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7904         let events = nodes[0].node.get_and_clear_pending_events();
7905         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7906         match events.last().unwrap() {
7907                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7908                 _ => panic!("Unexpected event"),
7909         }
7910         let first;
7911         let feerate_1;
7912         let penalty_txn;
7913         {
7914                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7915                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7916                 // Verify claim tx are spending revoked HTLC txn
7917
7918                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7919                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7920                 // which are included in the same block (they are broadcasted because we scan the
7921                 // transactions linearly and generate claims as we go, they likely should be removed in the
7922                 // future).
7923                 assert_eq!(node_txn[0].input.len(), 1);
7924                 check_spends!(node_txn[0], revoked_local_txn[0]);
7925                 assert_eq!(node_txn[1].input.len(), 1);
7926                 check_spends!(node_txn[1], revoked_local_txn[0]);
7927                 assert_eq!(node_txn[2].input.len(), 1);
7928                 check_spends!(node_txn[2], revoked_local_txn[0]);
7929
7930                 // Each of the three justice transactions claim a separate (single) output of the three
7931                 // available, which we check here:
7932                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7933                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7934                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7935
7936                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7937                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7938
7939                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7940                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7941                 // a remote commitment tx has already been confirmed).
7942                 check_spends!(node_txn[3], chan.3);
7943
7944                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7945                 // output, checked above).
7946                 assert_eq!(node_txn[4].input.len(), 2);
7947                 assert_eq!(node_txn[4].output.len(), 1);
7948                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7949
7950                 first = node_txn[4].txid();
7951                 // Store both feerates for later comparison
7952                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7953                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7954                 penalty_txn = vec![node_txn[2].clone()];
7955                 node_txn.clear();
7956         }
7957
7958         // Connect one more block to see if bumped penalty are issued for HTLC txn
7959         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7960         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7961         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7962         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7963         {
7964                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7965                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7966
7967                 check_spends!(node_txn[0], revoked_local_txn[0]);
7968                 check_spends!(node_txn[1], revoked_local_txn[0]);
7969                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7970                 if 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                 } else {
7973                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7974                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7975                 }
7976
7977                 node_txn.clear();
7978         };
7979
7980         // Few more blocks to confirm penalty txn
7981         connect_blocks(&nodes[0], 4);
7982         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7983         let header_144 = connect_blocks(&nodes[0], 9);
7984         let node_txn = {
7985                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7986                 assert_eq!(node_txn.len(), 1);
7987
7988                 assert_eq!(node_txn[0].input.len(), 2);
7989                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7990                 // Verify bumped tx is different and 25% bump heuristic
7991                 assert_ne!(first, node_txn[0].txid());
7992                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7993                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7994                 assert!(feerate_2 * 100 > feerate_1 * 125);
7995                 let txn = vec![node_txn[0].clone()];
7996                 node_txn.clear();
7997                 txn
7998         };
7999         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
8000         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8001         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
8002         connect_blocks(&nodes[0], 20);
8003         {
8004                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8005                 // We verify than no new transaction has been broadcast because previously
8006                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
8007                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
8008                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
8009                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
8010                 // up bumped justice generation.
8011                 assert_eq!(node_txn.len(), 0);
8012                 node_txn.clear();
8013         }
8014         check_closed_broadcast!(nodes[0], true);
8015         check_added_monitors!(nodes[0], 1);
8016 }
8017
8018 #[test]
8019 fn test_bump_penalty_txn_on_remote_commitment() {
8020         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
8021         // we're able to claim outputs on remote commitment transaction before timelocks expiration
8022
8023         // Create 2 HTLCs
8024         // Provide preimage for one
8025         // Check aggregation
8026
8027         let chanmon_cfgs = create_chanmon_cfgs(2);
8028         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8029         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8030         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8031
8032         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8033         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
8034         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8035
8036         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8037         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8038         assert_eq!(remote_txn[0].output.len(), 4);
8039         assert_eq!(remote_txn[0].input.len(), 1);
8040         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8041
8042         // Claim a HTLC without revocation (provide B monitor with preimage)
8043         nodes[1].node.claim_funds(payment_preimage);
8044         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
8045         mine_transaction(&nodes[1], &remote_txn[0]);
8046         check_added_monitors!(nodes[1], 2);
8047         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8048
8049         // One or more claim tx should have been broadcast, check it
8050         let timeout;
8051         let preimage;
8052         let preimage_bump;
8053         let feerate_timeout;
8054         let feerate_preimage;
8055         {
8056                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8057                 // 9 transactions including:
8058                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8059                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8060                 // 2 * HTLC-Success (one RBF bump we'll check later)
8061                 // 1 * HTLC-Timeout
8062                 assert_eq!(node_txn.len(), 8);
8063                 assert_eq!(node_txn[0].input.len(), 1);
8064                 assert_eq!(node_txn[6].input.len(), 1);
8065                 check_spends!(node_txn[0], remote_txn[0]);
8066                 check_spends!(node_txn[6], remote_txn[0]);
8067
8068                 check_spends!(node_txn[1], chan.3);
8069                 check_spends!(node_txn[2], node_txn[1]);
8070
8071                 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
8072                         preimage_bump = node_txn[3].clone();
8073                         check_spends!(node_txn[3], remote_txn[0]);
8074
8075                         assert_eq!(node_txn[1], node_txn[4]);
8076                         assert_eq!(node_txn[2], node_txn[5]);
8077                 } else {
8078                         preimage_bump = node_txn[7].clone();
8079                         check_spends!(node_txn[7], remote_txn[0]);
8080                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8081
8082                         assert_eq!(node_txn[1], node_txn[3]);
8083                         assert_eq!(node_txn[2], node_txn[4]);
8084                 }
8085
8086                 timeout = node_txn[6].txid();
8087                 let index = node_txn[6].input[0].previous_output.vout;
8088                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8089                 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8090
8091                 preimage = node_txn[0].txid();
8092                 let index = node_txn[0].input[0].previous_output.vout;
8093                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8094                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8095
8096                 node_txn.clear();
8097         };
8098         assert_ne!(feerate_timeout, 0);
8099         assert_ne!(feerate_preimage, 0);
8100
8101         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8102         connect_blocks(&nodes[1], 15);
8103         {
8104                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8105                 assert_eq!(node_txn.len(), 1);
8106                 assert_eq!(node_txn[0].input.len(), 1);
8107                 assert_eq!(preimage_bump.input.len(), 1);
8108                 check_spends!(node_txn[0], remote_txn[0]);
8109                 check_spends!(preimage_bump, remote_txn[0]);
8110
8111                 let index = preimage_bump.input[0].previous_output.vout;
8112                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8113                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8114                 assert!(new_feerate * 100 > feerate_timeout * 125);
8115                 assert_ne!(timeout, preimage_bump.txid());
8116
8117                 let index = node_txn[0].input[0].previous_output.vout;
8118                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8119                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8120                 assert!(new_feerate * 100 > feerate_preimage * 125);
8121                 assert_ne!(preimage, node_txn[0].txid());
8122
8123                 node_txn.clear();
8124         }
8125
8126         nodes[1].node.get_and_clear_pending_events();
8127         nodes[1].node.get_and_clear_pending_msg_events();
8128 }
8129
8130 #[test]
8131 fn test_counterparty_raa_skip_no_crash() {
8132         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8133         // commitment transaction, we would have happily carried on and provided them the next
8134         // commitment transaction based on one RAA forward. This would probably eventually have led to
8135         // channel closure, but it would not have resulted in funds loss. Still, our
8136         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8137         // check simply that the channel is closed in response to such an RAA, but don't check whether
8138         // we decide to punish our counterparty for revoking their funds (as we don't currently
8139         // implement that).
8140         let chanmon_cfgs = create_chanmon_cfgs(2);
8141         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8142         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8143         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8144         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8145
8146         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8147         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8148
8149         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8150
8151         // Make signer believe we got a counterparty signature, so that it allows the revocation
8152         keys.get_enforcement_state().last_holder_commitment -= 1;
8153         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8154
8155         // Must revoke without gaps
8156         keys.get_enforcement_state().last_holder_commitment -= 1;
8157         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8158
8159         keys.get_enforcement_state().last_holder_commitment -= 1;
8160         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8161                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8162
8163         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8164                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8165         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8166         check_added_monitors!(nodes[1], 1);
8167         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8168 }
8169
8170 #[test]
8171 fn test_bump_txn_sanitize_tracking_maps() {
8172         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8173         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8174
8175         let chanmon_cfgs = create_chanmon_cfgs(2);
8176         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8177         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8178         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8179
8180         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8181         // Lock HTLC in both directions
8182         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
8183         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
8184
8185         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8186         assert_eq!(revoked_local_txn[0].input.len(), 1);
8187         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8188
8189         // Revoke local commitment tx
8190         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
8191
8192         // Broadcast set of revoked txn on A
8193         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8194         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
8195         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8196
8197         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8198         check_closed_broadcast!(nodes[0], true);
8199         check_added_monitors!(nodes[0], 1);
8200         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8201         let penalty_txn = {
8202                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8203                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8204                 check_spends!(node_txn[0], revoked_local_txn[0]);
8205                 check_spends!(node_txn[1], revoked_local_txn[0]);
8206                 check_spends!(node_txn[2], revoked_local_txn[0]);
8207                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8208                 node_txn.clear();
8209                 penalty_txn
8210         };
8211         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8212         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8213         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8214         {
8215                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8216                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8217                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8218         }
8219 }
8220
8221 #[test]
8222 fn test_pending_claimed_htlc_no_balance_underflow() {
8223         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8224         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8225         let chanmon_cfgs = create_chanmon_cfgs(2);
8226         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8227         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8228         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8229         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8230
8231         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8232         nodes[1].node.claim_funds(payment_preimage);
8233         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8234         check_added_monitors!(nodes[1], 1);
8235         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8236
8237         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8238         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8239         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8240         check_added_monitors!(nodes[0], 1);
8241         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8242
8243         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8244         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8245         // can get our balance.
8246
8247         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8248         // the public key of the only hop. This works around ChannelDetails not showing the
8249         // almost-claimed HTLC as available balance.
8250         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8251         route.payment_params = None; // This is all wrong, but unnecessary
8252         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8253         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8254         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8255
8256         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8257 }
8258
8259 #[test]
8260 fn test_channel_conf_timeout() {
8261         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8262         // confirm within 2016 blocks, as recommended by BOLT 2.
8263         let chanmon_cfgs = create_chanmon_cfgs(2);
8264         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8265         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8266         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8267
8268         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8269
8270         // The outbound node should wait forever for confirmation:
8271         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8272         // copied here instead of directly referencing the constant.
8273         connect_blocks(&nodes[0], 2016);
8274         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8275
8276         // The inbound node should fail the channel after exactly 2016 blocks
8277         connect_blocks(&nodes[1], 2015);
8278         check_added_monitors!(nodes[1], 0);
8279         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8280
8281         connect_blocks(&nodes[1], 1);
8282         check_added_monitors!(nodes[1], 1);
8283         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8284         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8285         assert_eq!(close_ev.len(), 1);
8286         match close_ev[0] {
8287                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8288                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8289                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8290                 },
8291                 _ => panic!("Unexpected event"),
8292         }
8293 }
8294
8295 #[test]
8296 fn test_override_channel_config() {
8297         let chanmon_cfgs = create_chanmon_cfgs(2);
8298         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8299         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8300         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8301
8302         // Node0 initiates a channel to node1 using the override config.
8303         let mut override_config = UserConfig::default();
8304         override_config.channel_handshake_config.our_to_self_delay = 200;
8305
8306         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8307
8308         // Assert the channel created by node0 is using the override config.
8309         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8310         assert_eq!(res.channel_flags, 0);
8311         assert_eq!(res.to_self_delay, 200);
8312 }
8313
8314 #[test]
8315 fn test_override_0msat_htlc_minimum() {
8316         let mut zero_config = UserConfig::default();
8317         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8318         let chanmon_cfgs = create_chanmon_cfgs(2);
8319         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8320         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8321         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8322
8323         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8324         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8325         assert_eq!(res.htlc_minimum_msat, 1);
8326
8327         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8328         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8329         assert_eq!(res.htlc_minimum_msat, 1);
8330 }
8331
8332 #[test]
8333 fn test_channel_update_has_correct_htlc_maximum_msat() {
8334         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8335         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8336         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8337         // 90% of the `channel_value`.
8338         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8339
8340         let mut config_30_percent = UserConfig::default();
8341         config_30_percent.channel_handshake_config.announced_channel = true;
8342         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8343         let mut config_50_percent = UserConfig::default();
8344         config_50_percent.channel_handshake_config.announced_channel = true;
8345         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8346         let mut config_95_percent = UserConfig::default();
8347         config_95_percent.channel_handshake_config.announced_channel = true;
8348         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8349         let mut config_100_percent = UserConfig::default();
8350         config_100_percent.channel_handshake_config.announced_channel = true;
8351         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8352
8353         let chanmon_cfgs = create_chanmon_cfgs(4);
8354         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8355         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)]);
8356         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8357
8358         let channel_value_satoshis = 100000;
8359         let channel_value_msat = channel_value_satoshis * 1000;
8360         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8361         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8362         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8363
8364         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001, InitFeatures::known(), InitFeatures::known());
8365         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001, InitFeatures::known(), InitFeatures::known());
8366
8367         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8368         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8369         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8370         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8371         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8372         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8373
8374         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8375         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8376         // `channel_value`.
8377         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8378         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8379         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8380         // `channel_value`.
8381         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8382 }
8383
8384 #[test]
8385 fn test_manually_accept_inbound_channel_request() {
8386         let mut manually_accept_conf = UserConfig::default();
8387         manually_accept_conf.manually_accept_inbound_channels = true;
8388         let chanmon_cfgs = create_chanmon_cfgs(2);
8389         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8390         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8391         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8392
8393         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8394         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8395
8396         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8397
8398         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8399         // accepting the inbound channel request.
8400         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8401
8402         let events = nodes[1].node.get_and_clear_pending_events();
8403         match events[0] {
8404                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8405                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8406                 }
8407                 _ => panic!("Unexpected event"),
8408         }
8409
8410         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8411         assert_eq!(accept_msg_ev.len(), 1);
8412
8413         match accept_msg_ev[0] {
8414                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8415                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8416                 }
8417                 _ => panic!("Unexpected event"),
8418         }
8419
8420         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8421
8422         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8423         assert_eq!(close_msg_ev.len(), 1);
8424
8425         let events = nodes[1].node.get_and_clear_pending_events();
8426         match events[0] {
8427                 Event::ChannelClosed { user_channel_id, .. } => {
8428                         assert_eq!(user_channel_id, 23);
8429                 }
8430                 _ => panic!("Unexpected event"),
8431         }
8432 }
8433
8434 #[test]
8435 fn test_manually_reject_inbound_channel_request() {
8436         let mut manually_accept_conf = UserConfig::default();
8437         manually_accept_conf.manually_accept_inbound_channels = true;
8438         let chanmon_cfgs = create_chanmon_cfgs(2);
8439         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8440         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8441         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8442
8443         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8444         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8445
8446         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8447
8448         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8449         // rejecting the inbound channel request.
8450         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8451
8452         let events = nodes[1].node.get_and_clear_pending_events();
8453         match events[0] {
8454                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8455                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8456                 }
8457                 _ => panic!("Unexpected event"),
8458         }
8459
8460         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8461         assert_eq!(close_msg_ev.len(), 1);
8462
8463         match close_msg_ev[0] {
8464                 MessageSendEvent::HandleError { ref node_id, .. } => {
8465                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8466                 }
8467                 _ => panic!("Unexpected event"),
8468         }
8469         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8470 }
8471
8472 #[test]
8473 fn test_reject_funding_before_inbound_channel_accepted() {
8474         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8475         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8476         // the node operator before the counterparty sends a `FundingCreated` message. If a
8477         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8478         // and the channel should be closed.
8479         let mut manually_accept_conf = UserConfig::default();
8480         manually_accept_conf.manually_accept_inbound_channels = true;
8481         let chanmon_cfgs = create_chanmon_cfgs(2);
8482         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8483         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8484         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8485
8486         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8487         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8488         let temp_channel_id = res.temporary_channel_id;
8489
8490         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8491
8492         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8493         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8494
8495         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8496         nodes[1].node.get_and_clear_pending_events();
8497
8498         // Get the `AcceptChannel` message of `nodes[1]` without calling
8499         // `ChannelManager::accept_inbound_channel`, which generates a
8500         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8501         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8502         // succeed when `nodes[0]` is passed to it.
8503         {
8504                 let mut lock;
8505                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8506                 let accept_chan_msg = channel.get_accept_channel_message();
8507                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8508         }
8509
8510         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8511
8512         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8513         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8514
8515         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8516         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8517
8518         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8519         assert_eq!(close_msg_ev.len(), 1);
8520
8521         let expected_err = "FundingCreated message received before the channel was accepted";
8522         match close_msg_ev[0] {
8523                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8524                         assert_eq!(msg.channel_id, temp_channel_id);
8525                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8526                         assert_eq!(msg.data, expected_err);
8527                 }
8528                 _ => panic!("Unexpected event"),
8529         }
8530
8531         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8532 }
8533
8534 #[test]
8535 fn test_can_not_accept_inbound_channel_twice() {
8536         let mut manually_accept_conf = UserConfig::default();
8537         manually_accept_conf.manually_accept_inbound_channels = true;
8538         let chanmon_cfgs = create_chanmon_cfgs(2);
8539         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8540         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8541         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8542
8543         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8544         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8545
8546         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8547
8548         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8549         // accepting the inbound channel request.
8550         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8551
8552         let events = nodes[1].node.get_and_clear_pending_events();
8553         match events[0] {
8554                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8555                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8556                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8557                         match api_res {
8558                                 Err(APIError::APIMisuseError { err }) => {
8559                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8560                                 },
8561                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8562                                 Err(_) => panic!("Unexpected Error"),
8563                         }
8564                 }
8565                 _ => panic!("Unexpected event"),
8566         }
8567
8568         // Ensure that the channel wasn't closed after attempting to accept it twice.
8569         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8570         assert_eq!(accept_msg_ev.len(), 1);
8571
8572         match accept_msg_ev[0] {
8573                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8574                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8575                 }
8576                 _ => panic!("Unexpected event"),
8577         }
8578 }
8579
8580 #[test]
8581 fn test_can_not_accept_unknown_inbound_channel() {
8582         let chanmon_cfg = create_chanmon_cfgs(2);
8583         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8584         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8585         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8586
8587         let unknown_channel_id = [0; 32];
8588         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8589         match api_res {
8590                 Err(APIError::ChannelUnavailable { err }) => {
8591                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8592                 },
8593                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8594                 Err(_) => panic!("Unexpected Error"),
8595         }
8596 }
8597
8598 #[test]
8599 fn test_simple_mpp() {
8600         // Simple test of sending a multi-path payment.
8601         let chanmon_cfgs = create_chanmon_cfgs(4);
8602         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8603         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8604         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8605
8606         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8607         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8608         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8609         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8610
8611         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8612         let path = route.paths[0].clone();
8613         route.paths.push(path);
8614         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8615         route.paths[0][0].short_channel_id = chan_1_id;
8616         route.paths[0][1].short_channel_id = chan_3_id;
8617         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8618         route.paths[1][0].short_channel_id = chan_2_id;
8619         route.paths[1][1].short_channel_id = chan_4_id;
8620         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8621         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8622 }
8623
8624 #[test]
8625 fn test_preimage_storage() {
8626         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8627         let chanmon_cfgs = create_chanmon_cfgs(2);
8628         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8629         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8630         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8631
8632         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8633
8634         {
8635                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8636                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8637                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8638                 check_added_monitors!(nodes[0], 1);
8639                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8640                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8641                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8642                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8643         }
8644         // Note that after leaving the above scope we have no knowledge of any arguments or return
8645         // values from previous calls.
8646         expect_pending_htlcs_forwardable!(nodes[1]);
8647         let events = nodes[1].node.get_and_clear_pending_events();
8648         assert_eq!(events.len(), 1);
8649         match events[0] {
8650                 Event::PaymentReceived { ref purpose, .. } => {
8651                         match &purpose {
8652                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8653                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8654                                 },
8655                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8656                         }
8657                 },
8658                 _ => panic!("Unexpected event"),
8659         }
8660 }
8661
8662 #[test]
8663 #[allow(deprecated)]
8664 fn test_secret_timeout() {
8665         // Simple test of payment secret storage time outs. After
8666         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8667         let chanmon_cfgs = create_chanmon_cfgs(2);
8668         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8669         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8670         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8671
8672         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8673
8674         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8675
8676         // We should fail to register the same payment hash twice, at least until we've connected a
8677         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8678         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8679                 assert_eq!(err, "Duplicate payment hash");
8680         } else { panic!(); }
8681         let mut block = {
8682                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8683                 Block {
8684                         header: BlockHeader {
8685                                 version: 0x2000000,
8686                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8687                                 merkle_root: Default::default(),
8688                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8689                         txdata: vec![],
8690                 }
8691         };
8692         connect_block(&nodes[1], &block);
8693         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8694                 assert_eq!(err, "Duplicate payment hash");
8695         } else { panic!(); }
8696
8697         // If we then connect the second block, we should be able to register the same payment hash
8698         // again (this time getting a new payment secret).
8699         block.header.prev_blockhash = block.header.block_hash();
8700         block.header.time += 1;
8701         connect_block(&nodes[1], &block);
8702         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8703         assert_ne!(payment_secret_1, our_payment_secret);
8704
8705         {
8706                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8707                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8708                 check_added_monitors!(nodes[0], 1);
8709                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8710                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8711                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8712                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8713         }
8714         // Note that after leaving the above scope we have no knowledge of any arguments or return
8715         // values from previous calls.
8716         expect_pending_htlcs_forwardable!(nodes[1]);
8717         let events = nodes[1].node.get_and_clear_pending_events();
8718         assert_eq!(events.len(), 1);
8719         match events[0] {
8720                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8721                         assert!(payment_preimage.is_none());
8722                         assert_eq!(payment_secret, our_payment_secret);
8723                         // We don't actually have the payment preimage with which to claim this payment!
8724                 },
8725                 _ => panic!("Unexpected event"),
8726         }
8727 }
8728
8729 #[test]
8730 fn test_bad_secret_hash() {
8731         // Simple test of unregistered payment hash/invalid payment secret handling
8732         let chanmon_cfgs = create_chanmon_cfgs(2);
8733         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8734         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8735         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8736
8737         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8738
8739         let random_payment_hash = PaymentHash([42; 32]);
8740         let random_payment_secret = PaymentSecret([43; 32]);
8741         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8742         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8743
8744         // All the below cases should end up being handled exactly identically, so we macro the
8745         // resulting events.
8746         macro_rules! handle_unknown_invalid_payment_data {
8747                 ($payment_hash: expr) => {
8748                         check_added_monitors!(nodes[0], 1);
8749                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8750                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8751                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8752                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8753
8754                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8755                         // again to process the pending backwards-failure of the HTLC
8756                         expect_pending_htlcs_forwardable!(nodes[1]);
8757                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8758                         check_added_monitors!(nodes[1], 1);
8759
8760                         // We should fail the payment back
8761                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8762                         match events.pop().unwrap() {
8763                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8764                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8765                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8766                                 },
8767                                 _ => panic!("Unexpected event"),
8768                         }
8769                 }
8770         }
8771
8772         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8773         // Error data is the HTLC value (100,000) and current block height
8774         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8775
8776         // Send a payment with the right payment hash but the wrong payment secret
8777         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8778         handle_unknown_invalid_payment_data!(our_payment_hash);
8779         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8780
8781         // Send a payment with a random payment hash, but the right payment secret
8782         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8783         handle_unknown_invalid_payment_data!(random_payment_hash);
8784         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8785
8786         // Send a payment with a random payment hash and random payment secret
8787         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8788         handle_unknown_invalid_payment_data!(random_payment_hash);
8789         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8790 }
8791
8792 #[test]
8793 fn test_update_err_monitor_lockdown() {
8794         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8795         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8796         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8797         //
8798         // This scenario may happen in a watchtower setup, where watchtower process a block height
8799         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8800         // commitment at same time.
8801
8802         let chanmon_cfgs = create_chanmon_cfgs(2);
8803         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8804         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8805         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8806
8807         // Create some initial channel
8808         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8809         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8810
8811         // Rebalance the network to generate htlc in the two directions
8812         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8813
8814         // Route a HTLC from node 0 to node 1 (but don't settle)
8815         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8816
8817         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8818         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8819         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8820         let persister = test_utils::TestPersister::new();
8821         let watchtower = {
8822                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8823                 let mut w = test_utils::TestVecWriter(Vec::new());
8824                 monitor.write(&mut w).unwrap();
8825                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8826                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8827                 assert!(new_monitor == *monitor);
8828                 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);
8829                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8830                 watchtower
8831         };
8832         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8833         let block = Block { header, txdata: vec![] };
8834         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8835         // transaction lock time requirements here.
8836         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8837         watchtower.chain_monitor.block_connected(&block, 200);
8838
8839         // Try to update ChannelMonitor
8840         nodes[1].node.claim_funds(preimage);
8841         check_added_monitors!(nodes[1], 1);
8842         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8843
8844         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8845         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8846         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8847         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8848                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8849                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8850                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8851                 } else { assert!(false); }
8852         } else { assert!(false); };
8853         // Our local monitor is in-sync and hasn't processed yet timeout
8854         check_added_monitors!(nodes[0], 1);
8855         let events = nodes[0].node.get_and_clear_pending_events();
8856         assert_eq!(events.len(), 1);
8857 }
8858
8859 #[test]
8860 fn test_concurrent_monitor_claim() {
8861         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8862         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8863         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8864         // state N+1 confirms. Alice claims output from state N+1.
8865
8866         let chanmon_cfgs = create_chanmon_cfgs(2);
8867         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8868         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8869         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8870
8871         // Create some initial channel
8872         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8873         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8874
8875         // Rebalance the network to generate htlc in the two directions
8876         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8877
8878         // Route a HTLC from node 0 to node 1 (but don't settle)
8879         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8880
8881         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8882         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8883         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8884         let persister = test_utils::TestPersister::new();
8885         let watchtower_alice = {
8886                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8887                 let mut w = test_utils::TestVecWriter(Vec::new());
8888                 monitor.write(&mut w).unwrap();
8889                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8890                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8891                 assert!(new_monitor == *monitor);
8892                 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);
8893                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8894                 watchtower
8895         };
8896         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8897         let block = Block { header, txdata: vec![] };
8898         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8899         // transaction lock time requirements here.
8900         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));
8901         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8902
8903         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8904         {
8905                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8906                 assert_eq!(txn.len(), 2);
8907                 txn.clear();
8908         }
8909
8910         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8911         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8912         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8913         let persister = test_utils::TestPersister::new();
8914         let watchtower_bob = {
8915                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8916                 let mut w = test_utils::TestVecWriter(Vec::new());
8917                 monitor.write(&mut w).unwrap();
8918                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8919                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8920                 assert!(new_monitor == *monitor);
8921                 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);
8922                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8923                 watchtower
8924         };
8925         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8926         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8927
8928         // Route another payment to generate another update with still previous HTLC pending
8929         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8930         {
8931                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8932         }
8933         check_added_monitors!(nodes[1], 1);
8934
8935         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8936         assert_eq!(updates.update_add_htlcs.len(), 1);
8937         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8938         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8939                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8940                         // Watchtower Alice should already have seen the block and reject the update
8941                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8942                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8943                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8944                 } else { assert!(false); }
8945         } else { assert!(false); };
8946         // Our local monitor is in-sync and hasn't processed yet timeout
8947         check_added_monitors!(nodes[0], 1);
8948
8949         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8950         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8951         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8952
8953         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8954         let bob_state_y;
8955         {
8956                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8957                 assert_eq!(txn.len(), 2);
8958                 bob_state_y = txn[0].clone();
8959                 txn.clear();
8960         };
8961
8962         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8963         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8964         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);
8965         {
8966                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8967                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8968                 // the onchain detection of the HTLC output
8969                 assert_eq!(htlc_txn.len(), 2);
8970                 check_spends!(htlc_txn[0], bob_state_y);
8971                 check_spends!(htlc_txn[1], bob_state_y);
8972         }
8973 }
8974
8975 #[test]
8976 fn test_pre_lockin_no_chan_closed_update() {
8977         // Test that if a peer closes a channel in response to a funding_created message we don't
8978         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8979         // message).
8980         //
8981         // Doing so would imply a channel monitor update before the initial channel monitor
8982         // registration, violating our API guarantees.
8983         //
8984         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8985         // then opening a second channel with the same funding output as the first (which is not
8986         // rejected because the first channel does not exist in the ChannelManager) and closing it
8987         // before receiving funding_signed.
8988         let chanmon_cfgs = create_chanmon_cfgs(2);
8989         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8990         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8991         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8992
8993         // Create an initial channel
8994         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8995         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8996         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8997         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8998         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8999
9000         // Move the first channel through the funding flow...
9001         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9002
9003         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9004         check_added_monitors!(nodes[0], 0);
9005
9006         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9007         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
9008         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
9009         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
9010         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
9011 }
9012
9013 #[test]
9014 fn test_htlc_no_detection() {
9015         // This test is a mutation to underscore the detection logic bug we had
9016         // before #653. HTLC value routed is above the remaining balance, thus
9017         // inverting HTLC and `to_remote` output. HTLC will come second and
9018         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
9019         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
9020         // outputs order detection for correct spending children filtring.
9021
9022         let chanmon_cfgs = create_chanmon_cfgs(2);
9023         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9024         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9025         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9026
9027         // Create some initial channels
9028         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9029
9030         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
9031         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
9032         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
9033         assert_eq!(local_txn[0].input.len(), 1);
9034         assert_eq!(local_txn[0].output.len(), 3);
9035         check_spends!(local_txn[0], chan_1.3);
9036
9037         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9038         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9039         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
9040         // We deliberately connect the local tx twice as this should provoke a failure calling
9041         // this test before #653 fix.
9042         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);
9043         check_closed_broadcast!(nodes[0], true);
9044         check_added_monitors!(nodes[0], 1);
9045         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
9046         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9047
9048         let htlc_timeout = {
9049                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9050                 assert_eq!(node_txn[1].input.len(), 1);
9051                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9052                 check_spends!(node_txn[1], local_txn[0]);
9053                 node_txn[1].clone()
9054         };
9055
9056         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9057         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9058         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9059         expect_payment_failed!(nodes[0], our_payment_hash, true);
9060 }
9061
9062 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9063         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9064         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9065         // Carol, Alice would be the upstream node, and Carol the downstream.)
9066         //
9067         // Steps of the test:
9068         // 1) Alice sends a HTLC to Carol through Bob.
9069         // 2) Carol doesn't settle the HTLC.
9070         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9071         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9072         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9073         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9074         // 5) Carol release the preimage to Bob off-chain.
9075         // 6) Bob claims the offered output on the broadcasted commitment.
9076         let chanmon_cfgs = create_chanmon_cfgs(3);
9077         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9078         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9079         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9080
9081         // Create some initial channels
9082         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9083         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9084
9085         // Steps (1) and (2):
9086         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9087         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9088
9089         // Check that Alice's commitment transaction now contains an output for this HTLC.
9090         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9091         check_spends!(alice_txn[0], chan_ab.3);
9092         assert_eq!(alice_txn[0].output.len(), 2);
9093         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9094         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9095         assert_eq!(alice_txn.len(), 2);
9096
9097         // Steps (3) and (4):
9098         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9099         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9100         let mut force_closing_node = 0; // Alice force-closes
9101         let mut counterparty_node = 1; // Bob if Alice force-closes
9102
9103         // Bob force-closes
9104         if !broadcast_alice {
9105                 force_closing_node = 1;
9106                 counterparty_node = 0;
9107         }
9108         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9109         check_closed_broadcast!(nodes[force_closing_node], true);
9110         check_added_monitors!(nodes[force_closing_node], 1);
9111         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9112         if go_onchain_before_fulfill {
9113                 let txn_to_broadcast = match broadcast_alice {
9114                         true => alice_txn.clone(),
9115                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9116                 };
9117                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9118                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9119                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9120                 if broadcast_alice {
9121                         check_closed_broadcast!(nodes[1], true);
9122                         check_added_monitors!(nodes[1], 1);
9123                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9124                 }
9125                 assert_eq!(bob_txn.len(), 1);
9126                 check_spends!(bob_txn[0], chan_ab.3);
9127         }
9128
9129         // Step (5):
9130         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9131         // process of removing the HTLC from their commitment transactions.
9132         nodes[2].node.claim_funds(payment_preimage);
9133         check_added_monitors!(nodes[2], 1);
9134         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9135
9136         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9137         assert!(carol_updates.update_add_htlcs.is_empty());
9138         assert!(carol_updates.update_fail_htlcs.is_empty());
9139         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9140         assert!(carol_updates.update_fee.is_none());
9141         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9142
9143         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9144         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9145         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9146         if !go_onchain_before_fulfill && broadcast_alice {
9147                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9148                 assert_eq!(events.len(), 1);
9149                 match events[0] {
9150                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9151                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9152                         },
9153                         _ => panic!("Unexpected event"),
9154                 };
9155         }
9156         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9157         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9158         // Carol<->Bob's updated commitment transaction info.
9159         check_added_monitors!(nodes[1], 2);
9160
9161         let events = nodes[1].node.get_and_clear_pending_msg_events();
9162         assert_eq!(events.len(), 2);
9163         let bob_revocation = match events[0] {
9164                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9165                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9166                         (*msg).clone()
9167                 },
9168                 _ => panic!("Unexpected event"),
9169         };
9170         let bob_updates = match events[1] {
9171                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9172                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9173                         (*updates).clone()
9174                 },
9175                 _ => panic!("Unexpected event"),
9176         };
9177
9178         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9179         check_added_monitors!(nodes[2], 1);
9180         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9181         check_added_monitors!(nodes[2], 1);
9182
9183         let events = nodes[2].node.get_and_clear_pending_msg_events();
9184         assert_eq!(events.len(), 1);
9185         let carol_revocation = match events[0] {
9186                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9187                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9188                         (*msg).clone()
9189                 },
9190                 _ => panic!("Unexpected event"),
9191         };
9192         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9193         check_added_monitors!(nodes[1], 1);
9194
9195         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9196         // here's where we put said channel's commitment tx on-chain.
9197         let mut txn_to_broadcast = alice_txn.clone();
9198         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9199         if !go_onchain_before_fulfill {
9200                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9201                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9202                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9203                 if broadcast_alice {
9204                         check_closed_broadcast!(nodes[1], true);
9205                         check_added_monitors!(nodes[1], 1);
9206                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9207                 }
9208                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9209                 if broadcast_alice {
9210                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9211                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9212                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9213                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9214                         // broadcasted.
9215                         assert_eq!(bob_txn.len(), 3);
9216                         check_spends!(bob_txn[1], chan_ab.3);
9217                 } else {
9218                         assert_eq!(bob_txn.len(), 2);
9219                         check_spends!(bob_txn[0], chan_ab.3);
9220                 }
9221         }
9222
9223         // Step (6):
9224         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9225         // broadcasted commitment transaction.
9226         {
9227                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9228                 if go_onchain_before_fulfill {
9229                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9230                         assert_eq!(bob_txn.len(), 2);
9231                 }
9232                 let script_weight = match broadcast_alice {
9233                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9234                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9235                 };
9236                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9237                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9238                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9239                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9240                 if broadcast_alice && !go_onchain_before_fulfill {
9241                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9242                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9243                 } else {
9244                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9245                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9246                 }
9247         }
9248 }
9249
9250 #[test]
9251 fn test_onchain_htlc_settlement_after_close() {
9252         do_test_onchain_htlc_settlement_after_close(true, true);
9253         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9254         do_test_onchain_htlc_settlement_after_close(true, false);
9255         do_test_onchain_htlc_settlement_after_close(false, false);
9256 }
9257
9258 #[test]
9259 fn test_duplicate_chan_id() {
9260         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9261         // already open we reject it and keep the old channel.
9262         //
9263         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9264         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9265         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9266         // updating logic for the existing channel.
9267         let chanmon_cfgs = create_chanmon_cfgs(2);
9268         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9269         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9270         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9271
9272         // Create an initial channel
9273         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9274         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9275         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9276         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9277
9278         // Try to create a second channel with the same temporary_channel_id as the first and check
9279         // that it is rejected.
9280         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9281         {
9282                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9283                 assert_eq!(events.len(), 1);
9284                 match events[0] {
9285                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9286                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9287                                 // first (valid) and second (invalid) channels are closed, given they both have
9288                                 // the same non-temporary channel_id. However, currently we do not, so we just
9289                                 // move forward with it.
9290                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9291                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9292                         },
9293                         _ => panic!("Unexpected event"),
9294                 }
9295         }
9296
9297         // Move the first channel through the funding flow...
9298         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9299
9300         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9301         check_added_monitors!(nodes[0], 0);
9302
9303         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9304         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9305         {
9306                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9307                 assert_eq!(added_monitors.len(), 1);
9308                 assert_eq!(added_monitors[0].0, funding_output);
9309                 added_monitors.clear();
9310         }
9311         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9312
9313         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9314         let channel_id = funding_outpoint.to_channel_id();
9315
9316         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9317         // temporary one).
9318
9319         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9320         // Technically this is allowed by the spec, but we don't support it and there's little reason
9321         // to. Still, it shouldn't cause any other issues.
9322         open_chan_msg.temporary_channel_id = channel_id;
9323         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9324         {
9325                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9326                 assert_eq!(events.len(), 1);
9327                 match events[0] {
9328                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9329                                 // Technically, at this point, nodes[1] would be justified in thinking both
9330                                 // channels are closed, but currently we do not, so we just move forward with it.
9331                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9332                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9333                         },
9334                         _ => panic!("Unexpected event"),
9335                 }
9336         }
9337
9338         // Now try to create a second channel which has a duplicate funding output.
9339         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9340         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9341         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9342         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9343         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9344
9345         let funding_created = {
9346                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9347                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9348                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9349                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9350                 // channelmanager in a possibly nonsense state instead).
9351                 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9352                 let logger = test_utils::TestLogger::new();
9353                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9354         };
9355         check_added_monitors!(nodes[0], 0);
9356         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9357         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9358         // still needs to be cleared here.
9359         check_added_monitors!(nodes[1], 1);
9360
9361         // ...still, nodes[1] will reject the duplicate channel.
9362         {
9363                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9364                 assert_eq!(events.len(), 1);
9365                 match events[0] {
9366                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9367                                 // Technically, at this point, nodes[1] would be justified in thinking both
9368                                 // channels are closed, but currently we do not, so we just move forward with it.
9369                                 assert_eq!(msg.channel_id, channel_id);
9370                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9371                         },
9372                         _ => panic!("Unexpected event"),
9373                 }
9374         }
9375
9376         // finally, finish creating the original channel and send a payment over it to make sure
9377         // everything is functional.
9378         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9379         {
9380                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9381                 assert_eq!(added_monitors.len(), 1);
9382                 assert_eq!(added_monitors[0].0, funding_output);
9383                 added_monitors.clear();
9384         }
9385
9386         let events_4 = nodes[0].node.get_and_clear_pending_events();
9387         assert_eq!(events_4.len(), 0);
9388         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9389         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9390
9391         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9392         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9393         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9394         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9395 }
9396
9397 #[test]
9398 fn test_error_chans_closed() {
9399         // Test that we properly handle error messages, closing appropriate channels.
9400         //
9401         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9402         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9403         // we can test various edge cases around it to ensure we don't regress.
9404         let chanmon_cfgs = create_chanmon_cfgs(3);
9405         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9406         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9407         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9408
9409         // Create some initial channels
9410         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9411         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9412         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9413
9414         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9415         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9416         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9417
9418         // Closing a channel from a different peer has no effect
9419         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9420         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9421
9422         // Closing one channel doesn't impact others
9423         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9424         check_added_monitors!(nodes[0], 1);
9425         check_closed_broadcast!(nodes[0], false);
9426         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9427         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9428         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9429         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);
9430         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);
9431
9432         // A null channel ID should close all channels
9433         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9434         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9435         check_added_monitors!(nodes[0], 2);
9436         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9437         let events = nodes[0].node.get_and_clear_pending_msg_events();
9438         assert_eq!(events.len(), 2);
9439         match events[0] {
9440                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9441                         assert_eq!(msg.contents.flags & 2, 2);
9442                 },
9443                 _ => panic!("Unexpected event"),
9444         }
9445         match events[1] {
9446                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9447                         assert_eq!(msg.contents.flags & 2, 2);
9448                 },
9449                 _ => panic!("Unexpected event"),
9450         }
9451         // Note that at this point users of a standard PeerHandler will end up calling
9452         // peer_disconnected with no_connection_possible set to false, duplicating the
9453         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9454         // users with their own peer handling logic. We duplicate the call here, however.
9455         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9456         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9457
9458         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9459         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9460         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9461 }
9462
9463 #[test]
9464 fn test_invalid_funding_tx() {
9465         // Test that we properly handle invalid funding transactions sent to us from a peer.
9466         //
9467         // Previously, all other major lightning implementations had failed to properly sanitize
9468         // funding transactions from their counterparties, leading to a multi-implementation critical
9469         // security vulnerability (though we always sanitized properly, we've previously had
9470         // un-released crashes in the sanitization process).
9471         //
9472         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9473         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9474         // gave up on it. We test this here by generating such a transaction.
9475         let chanmon_cfgs = create_chanmon_cfgs(2);
9476         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9477         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9478         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9479
9480         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9481         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
9482         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9483
9484         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9485
9486         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9487         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9488         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9489         // its length.
9490         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9491         assert!(chan_utils::HTLCType::scriptlen_to_htlctype(wit_program.len()).unwrap() ==
9492                 chan_utils::HTLCType::AcceptedHTLC);
9493
9494         let wit_program_script: Script = wit_program.clone().into();
9495         for output in tx.output.iter_mut() {
9496                 // Make the confirmed funding transaction have a bogus script_pubkey
9497                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9498         }
9499
9500         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9501         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()));
9502         check_added_monitors!(nodes[1], 1);
9503
9504         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()));
9505         check_added_monitors!(nodes[0], 1);
9506
9507         let events_1 = nodes[0].node.get_and_clear_pending_events();
9508         assert_eq!(events_1.len(), 0);
9509
9510         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9511         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9512         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9513
9514         let expected_err = "funding tx had wrong script/value or output index";
9515         confirm_transaction_at(&nodes[1], &tx, 1);
9516         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9517         check_added_monitors!(nodes[1], 1);
9518         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9519         assert_eq!(events_2.len(), 1);
9520         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9521                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9522                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9523                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9524                 } else { panic!(); }
9525         } else { panic!(); }
9526         assert_eq!(nodes[1].node.list_channels().len(), 0);
9527
9528         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9529         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9530         // as its not 32 bytes long.
9531         let mut spend_tx = Transaction {
9532                 version: 2i32, lock_time: 0,
9533                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9534                         previous_output: BitcoinOutPoint {
9535                                 txid: tx.txid(),
9536                                 vout: idx as u32,
9537                         },
9538                         script_sig: Script::new(),
9539                         sequence: 0xfffffffd,
9540                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9541                 }).collect(),
9542                 output: vec![TxOut {
9543                         value: 1000,
9544                         script_pubkey: Script::new(),
9545                 }]
9546         };
9547         check_spends!(spend_tx, tx);
9548         mine_transaction(&nodes[1], &spend_tx);
9549 }
9550
9551 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9552         // In the first version of the chain::Confirm interface, after a refactor was made to not
9553         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9554         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9555         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9556         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9557         // spending transaction until height N+1 (or greater). This was due to the way
9558         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9559         // spending transaction at the height the input transaction was confirmed at, not whether we
9560         // should broadcast a spending transaction at the current height.
9561         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9562         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9563         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9564         // until we learned about an additional block.
9565         //
9566         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9567         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9568         let chanmon_cfgs = create_chanmon_cfgs(3);
9569         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9570         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9571         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9572         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9573
9574         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9575         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9576         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9577         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9578         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9579
9580         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9581         check_closed_broadcast!(nodes[1], true);
9582         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9583         check_added_monitors!(nodes[1], 1);
9584         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9585         assert_eq!(node_txn.len(), 1);
9586
9587         let conf_height = nodes[1].best_block_info().1;
9588         if !test_height_before_timelock {
9589                 connect_blocks(&nodes[1], 24 * 6);
9590         }
9591         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9592                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9593         if test_height_before_timelock {
9594                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9595                 // generate any events or broadcast any transactions
9596                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9597                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9598         } else {
9599                 // We should broadcast an HTLC transaction spending our funding transaction first
9600                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9601                 assert_eq!(spending_txn.len(), 2);
9602                 assert_eq!(spending_txn[0], node_txn[0]);
9603                 check_spends!(spending_txn[1], node_txn[0]);
9604                 // We should also generate a SpendableOutputs event with the to_self output (as its
9605                 // timelock is up).
9606                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9607                 assert_eq!(descriptor_spend_txn.len(), 1);
9608
9609                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9610                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9611                 // additional block built on top of the current chain.
9612                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9613                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9614                 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 }]);
9615                 check_added_monitors!(nodes[1], 1);
9616
9617                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9618                 assert!(updates.update_add_htlcs.is_empty());
9619                 assert!(updates.update_fulfill_htlcs.is_empty());
9620                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9621                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9622                 assert!(updates.update_fee.is_none());
9623                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9624                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9625                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9626         }
9627 }
9628
9629 #[test]
9630 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9631         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9632         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9633 }
9634
9635 #[test]
9636 fn test_forwardable_regen() {
9637         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9638         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9639         // HTLCs.
9640         // We test it for both payment receipt and payment forwarding.
9641
9642         let chanmon_cfgs = create_chanmon_cfgs(3);
9643         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9644         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9645         let persister: test_utils::TestPersister;
9646         let new_chain_monitor: test_utils::TestChainMonitor;
9647         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9648         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9649         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9650         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9651
9652         // First send a payment to nodes[1]
9653         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9654         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9655         check_added_monitors!(nodes[0], 1);
9656
9657         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9658         assert_eq!(events.len(), 1);
9659         let payment_event = SendEvent::from_event(events.pop().unwrap());
9660         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9661         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9662
9663         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9664
9665         // Next send a payment which is forwarded by nodes[1]
9666         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9667         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9668         check_added_monitors!(nodes[0], 1);
9669
9670         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9671         assert_eq!(events.len(), 1);
9672         let payment_event = SendEvent::from_event(events.pop().unwrap());
9673         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9674         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9675
9676         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9677         // generated
9678         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9679
9680         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9681         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9682         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9683
9684         let nodes_1_serialized = nodes[1].node.encode();
9685         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9686         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9687         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9688         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9689
9690         persister = test_utils::TestPersister::new();
9691         let keys_manager = &chanmon_cfgs[1].keys_manager;
9692         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);
9693         nodes[1].chain_monitor = &new_chain_monitor;
9694
9695         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9696         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9697                 &mut chan_0_monitor_read, keys_manager).unwrap();
9698         assert!(chan_0_monitor_read.is_empty());
9699         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9700         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9701                 &mut chan_1_monitor_read, keys_manager).unwrap();
9702         assert!(chan_1_monitor_read.is_empty());
9703
9704         let mut nodes_1_read = &nodes_1_serialized[..];
9705         let (_, nodes_1_deserialized_tmp) = {
9706                 let mut channel_monitors = HashMap::new();
9707                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9708                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9709                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9710                         default_config: UserConfig::default(),
9711                         keys_manager,
9712                         fee_estimator: node_cfgs[1].fee_estimator,
9713                         chain_monitor: nodes[1].chain_monitor,
9714                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9715                         logger: nodes[1].logger,
9716                         channel_monitors,
9717                 }).unwrap()
9718         };
9719         nodes_1_deserialized = nodes_1_deserialized_tmp;
9720         assert!(nodes_1_read.is_empty());
9721
9722         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9723         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9724         nodes[1].node = &nodes_1_deserialized;
9725         check_added_monitors!(nodes[1], 2);
9726
9727         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9728         // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9729         // the commitment state.
9730         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9731
9732         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9733
9734         expect_pending_htlcs_forwardable!(nodes[1]);
9735         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9736         check_added_monitors!(nodes[1], 1);
9737
9738         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9739         assert_eq!(events.len(), 1);
9740         let payment_event = SendEvent::from_event(events.pop().unwrap());
9741         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9742         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9743         expect_pending_htlcs_forwardable!(nodes[2]);
9744         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9745
9746         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9747         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9748 }
9749
9750 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9751         let chanmon_cfgs = create_chanmon_cfgs(2);
9752         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9753         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9754         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9755
9756         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9757
9758         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9759                 .with_features(InvoiceFeatures::known());
9760         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9761
9762         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9763
9764         {
9765                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9766                 check_added_monitors!(nodes[0], 1);
9767                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9768                 assert_eq!(events.len(), 1);
9769                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9770                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9771                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9772         }
9773         expect_pending_htlcs_forwardable!(nodes[1]);
9774         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9775
9776         {
9777                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9778                 check_added_monitors!(nodes[0], 1);
9779                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9780                 assert_eq!(events.len(), 1);
9781                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9782                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9783                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9784                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9785                 // assume the second is a privacy attack (no longer particularly relevant
9786                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9787                 // the first HTLC delivered above.
9788         }
9789
9790         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9791         nodes[1].node.process_pending_htlc_forwards();
9792
9793         if test_for_second_fail_panic {
9794                 // Now we go fail back the first HTLC from the user end.
9795                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9796
9797                 let expected_destinations = vec![
9798                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9799                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9800                 ];
9801                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9802                 nodes[1].node.process_pending_htlc_forwards();
9803
9804                 check_added_monitors!(nodes[1], 1);
9805                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9806                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9807
9808                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9809                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9810                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9811
9812                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9813                 assert_eq!(failure_events.len(), 2);
9814                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9815                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9816         } else {
9817                 // Let the second HTLC fail and claim the first
9818                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9819                 nodes[1].node.process_pending_htlc_forwards();
9820
9821                 check_added_monitors!(nodes[1], 1);
9822                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9823                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9824                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9825
9826                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9827
9828                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9829         }
9830 }
9831
9832 #[test]
9833 fn test_dup_htlc_second_fail_panic() {
9834         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9835         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9836         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9837         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9838         do_test_dup_htlc_second_rejected(true);
9839 }
9840
9841 #[test]
9842 fn test_dup_htlc_second_rejected() {
9843         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9844         // simply reject the second HTLC but are still able to claim the first HTLC.
9845         do_test_dup_htlc_second_rejected(false);
9846 }
9847
9848 #[test]
9849 fn test_inconsistent_mpp_params() {
9850         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9851         // such HTLC and allow the second to stay.
9852         let chanmon_cfgs = create_chanmon_cfgs(4);
9853         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9854         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9855         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9856
9857         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9858         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9859         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9860         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9861
9862         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9863                 .with_features(InvoiceFeatures::known());
9864         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9865         assert_eq!(route.paths.len(), 2);
9866         route.paths.sort_by(|path_a, _| {
9867                 // Sort the path so that the path through nodes[1] comes first
9868                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9869                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9870         });
9871         let payment_params_opt = Some(payment_params);
9872
9873         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9874
9875         let cur_height = nodes[0].best_block_info().1;
9876         let payment_id = PaymentId([42; 32]);
9877         {
9878                 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();
9879                 check_added_monitors!(nodes[0], 1);
9880
9881                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9882                 assert_eq!(events.len(), 1);
9883                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9884         }
9885         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9886
9887         {
9888                 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();
9889                 check_added_monitors!(nodes[0], 1);
9890
9891                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9892                 assert_eq!(events.len(), 1);
9893                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9894
9895                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9896                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9897
9898                 expect_pending_htlcs_forwardable!(nodes[2]);
9899                 check_added_monitors!(nodes[2], 1);
9900
9901                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9902                 assert_eq!(events.len(), 1);
9903                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9904
9905                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9906                 check_added_monitors!(nodes[3], 0);
9907                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9908
9909                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9910                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9911                 // post-payment_secrets) and fail back the new HTLC.
9912         }
9913         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9914         nodes[3].node.process_pending_htlc_forwards();
9915         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9916         nodes[3].node.process_pending_htlc_forwards();
9917
9918         check_added_monitors!(nodes[3], 1);
9919
9920         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9921         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9922         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9923
9924         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 }]);
9925         check_added_monitors!(nodes[2], 1);
9926
9927         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9928         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9929         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9930
9931         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9932
9933         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();
9934         check_added_monitors!(nodes[0], 1);
9935
9936         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9937         assert_eq!(events.len(), 1);
9938         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9939
9940         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9941 }
9942
9943 #[test]
9944 fn test_keysend_payments_to_public_node() {
9945         let chanmon_cfgs = create_chanmon_cfgs(2);
9946         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9947         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9948         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9949
9950         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9951         let network_graph = nodes[0].network_graph;
9952         let payer_pubkey = nodes[0].node.get_our_node_id();
9953         let payee_pubkey = nodes[1].node.get_our_node_id();
9954         let route_params = RouteParameters {
9955                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9956                 final_value_msat: 10000,
9957                 final_cltv_expiry_delta: 40,
9958         };
9959         let scorer = test_utils::TestScorer::with_penalty(0);
9960         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9961         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9962
9963         let test_preimage = PaymentPreimage([42; 32]);
9964         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9965         check_added_monitors!(nodes[0], 1);
9966         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9967         assert_eq!(events.len(), 1);
9968         let event = events.pop().unwrap();
9969         let path = vec![&nodes[1]];
9970         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9971         claim_payment(&nodes[0], &path, test_preimage);
9972 }
9973
9974 #[test]
9975 fn test_keysend_payments_to_private_node() {
9976         let chanmon_cfgs = create_chanmon_cfgs(2);
9977         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9978         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9979         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9980
9981         let payer_pubkey = nodes[0].node.get_our_node_id();
9982         let payee_pubkey = nodes[1].node.get_our_node_id();
9983         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9984         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9985
9986         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9987         let route_params = RouteParameters {
9988                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9989                 final_value_msat: 10000,
9990                 final_cltv_expiry_delta: 40,
9991         };
9992         let network_graph = nodes[0].network_graph;
9993         let first_hops = nodes[0].node.list_usable_channels();
9994         let scorer = test_utils::TestScorer::with_penalty(0);
9995         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9996         let route = find_route(
9997                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9998                 nodes[0].logger, &scorer, &random_seed_bytes
9999         ).unwrap();
10000
10001         let test_preimage = PaymentPreimage([42; 32]);
10002         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
10003         check_added_monitors!(nodes[0], 1);
10004         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10005         assert_eq!(events.len(), 1);
10006         let event = events.pop().unwrap();
10007         let path = vec![&nodes[1]];
10008         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
10009         claim_payment(&nodes[0], &path, test_preimage);
10010 }
10011
10012 #[test]
10013 fn test_double_partial_claim() {
10014         // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
10015         // time out, the sender resends only some of the MPP parts, then the user processes the
10016         // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
10017         // amount.
10018         let chanmon_cfgs = create_chanmon_cfgs(4);
10019         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10020         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10021         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10022
10023         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10024         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10025         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10026         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10027
10028         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10029         assert_eq!(route.paths.len(), 2);
10030         route.paths.sort_by(|path_a, _| {
10031                 // Sort the path so that the path through nodes[1] comes first
10032                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10033                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10034         });
10035
10036         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
10037         // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
10038         // amount of time to respond to.
10039
10040         // Connect some blocks to time out the payment
10041         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
10042         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
10043
10044         let failed_destinations = vec![
10045                 HTLCDestination::FailedPayment { payment_hash },
10046                 HTLCDestination::FailedPayment { payment_hash },
10047         ];
10048         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
10049
10050         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
10051
10052         // nodes[1] now retries one of the two paths...
10053         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10054         check_added_monitors!(nodes[0], 2);
10055
10056         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10057         assert_eq!(events.len(), 2);
10058         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10059
10060         // At this point nodes[3] has received one half of the payment, and the user goes to handle
10061         // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
10062         nodes[3].node.claim_funds(payment_preimage);
10063         check_added_monitors!(nodes[3], 0);
10064         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
10065 }
10066
10067 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10068         // Test what happens if a node receives an MPP payment, claims it, but crashes before
10069         // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10070         // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10071         // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10072         // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10073         // not have the preimage tied to the still-pending HTLC.
10074         //
10075         // To get to the correct state, on startup we should propagate the preimage to the
10076         // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10077         // receiving the preimage without a state update.
10078         //
10079         // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10080         // definitely claimed.
10081         let chanmon_cfgs = create_chanmon_cfgs(4);
10082         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10083         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10084
10085         let persister: test_utils::TestPersister;
10086         let new_chain_monitor: test_utils::TestChainMonitor;
10087         let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10088
10089         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10090
10091         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10092         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10093         let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10094         let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10095
10096         // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10097         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10098         assert_eq!(route.paths.len(), 2);
10099         route.paths.sort_by(|path_a, _| {
10100                 // Sort the path so that the path through nodes[1] comes first
10101                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10102                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10103         });
10104
10105         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10106         check_added_monitors!(nodes[0], 2);
10107
10108         // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10109         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10110         assert_eq!(send_events.len(), 2);
10111         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);
10112         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);
10113
10114         // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10115         // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10116         let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10117         if !persist_both_monitors {
10118                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10119                         if outpoint.to_channel_id() == chan_id_not_persisted {
10120                                 assert!(original_monitor.0.is_empty());
10121                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10122                         }
10123                 }
10124         }
10125
10126         let mut original_manager = test_utils::TestVecWriter(Vec::new());
10127         nodes[3].node.write(&mut original_manager).unwrap();
10128
10129         expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10130
10131         nodes[3].node.claim_funds(payment_preimage);
10132         check_added_monitors!(nodes[3], 2);
10133         expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10134
10135         // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10136         // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10137         // with the old ChannelManager.
10138         let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10139         for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10140                 if outpoint.to_channel_id() == chan_id_persisted {
10141                         assert!(updated_monitor.0.is_empty());
10142                         nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10143                 }
10144         }
10145         // If `persist_both_monitors` is set, get the second monitor here as well
10146         if persist_both_monitors {
10147                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10148                         if outpoint.to_channel_id() == chan_id_not_persisted {
10149                                 assert!(original_monitor.0.is_empty());
10150                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10151                         }
10152                 }
10153         }
10154
10155         // Now restart nodes[3].
10156         persister = test_utils::TestPersister::new();
10157         let keys_manager = &chanmon_cfgs[3].keys_manager;
10158         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);
10159         nodes[3].chain_monitor = &new_chain_monitor;
10160         let mut monitors = Vec::new();
10161         for mut monitor_data in [original_monitor, updated_monitor].iter() {
10162                 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10163                 monitors.push(deserialized_monitor);
10164         }
10165
10166         let config = UserConfig::default();
10167         nodes_3_deserialized = {
10168                 let mut channel_monitors = HashMap::new();
10169                 for monitor in monitors.iter_mut() {
10170                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10171                 }
10172                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10173                         default_config: config,
10174                         keys_manager,
10175                         fee_estimator: node_cfgs[3].fee_estimator,
10176                         chain_monitor: nodes[3].chain_monitor,
10177                         tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10178                         logger: nodes[3].logger,
10179                         channel_monitors,
10180                 }).unwrap().1
10181         };
10182         nodes[3].node = &nodes_3_deserialized;
10183
10184         for monitor in monitors {
10185                 // On startup the preimage should have been copied into the non-persisted monitor:
10186                 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10187                 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10188         }
10189         check_added_monitors!(nodes[3], 2);
10190
10191         nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10192         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10193
10194         // During deserialization, we should have closed one channel and broadcast its latest
10195         // commitment transaction. We should also still have the original PaymentReceived event we
10196         // never finished processing.
10197         let events = nodes[3].node.get_and_clear_pending_events();
10198         assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10199         if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10200         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10201         if persist_both_monitors {
10202                 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10203         }
10204
10205         // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10206         // ChannelManager prior to handling the original one.
10207         if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10208                 events[if persist_both_monitors { 3 } else { 2 }]
10209         {
10210                 assert_eq!(payment_hash, our_payment_hash);
10211         } else { panic!(); }
10212
10213         assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10214         if !persist_both_monitors {
10215                 // If one of the two channels is still live, reveal the payment preimage over it.
10216
10217                 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10218                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10219                 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10220                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10221
10222                 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10223                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10224                 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10225
10226                 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10227
10228                 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10229                 // claim should fly.
10230                 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10231                 check_added_monitors!(nodes[3], 1);
10232                 assert_eq!(ds_msgs.len(), 2);
10233                 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10234
10235                 let cs_updates = match ds_msgs[0] {
10236                         MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10237                                 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10238                                 check_added_monitors!(nodes[2], 1);
10239                                 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10240                                 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10241                                 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10242                                 cs_updates
10243                         }
10244                         _ => panic!(),
10245                 };
10246
10247                 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10248                 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10249                 expect_payment_sent!(nodes[0], payment_preimage);
10250         }
10251 }
10252
10253 #[test]
10254 fn test_partial_claim_before_restart() {
10255         do_test_partial_claim_before_restart(false);
10256         do_test_partial_claim_before_restart(true);
10257 }
10258
10259 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10260 #[derive(Clone, Copy, PartialEq)]
10261 enum ExposureEvent {
10262         /// Breach occurs at HTLC forwarding (see `send_htlc`)
10263         AtHTLCForward,
10264         /// Breach occurs at HTLC reception (see `update_add_htlc`)
10265         AtHTLCReception,
10266         /// Breach occurs at outbound update_fee (see `send_update_fee`)
10267         AtUpdateFeeOutbound,
10268 }
10269
10270 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10271         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10272         // policy.
10273         //
10274         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10275         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10276         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10277         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10278         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10279         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10280         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10281         // might be available again for HTLC processing once the dust bandwidth has cleared up.
10282
10283         let chanmon_cfgs = create_chanmon_cfgs(2);
10284         let mut config = test_default_channel_config();
10285         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10286         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10287         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10288         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10289
10290         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10291         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10292         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10293         open_channel.max_accepted_htlcs = 60;
10294         if on_holder_tx {
10295                 open_channel.dust_limit_satoshis = 546;
10296         }
10297         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10298         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10299         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10300
10301         let opt_anchors = false;
10302
10303         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10304
10305         if on_holder_tx {
10306                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10307                         chan.holder_dust_limit_satoshis = 546;
10308                 }
10309         }
10310
10311         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10312         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()));
10313         check_added_monitors!(nodes[1], 1);
10314
10315         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()));
10316         check_added_monitors!(nodes[0], 1);
10317
10318         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10319         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10320         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10321
10322         let dust_buffer_feerate = {
10323                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10324                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10325                 chan.get_dust_buffer_feerate(None) as u64
10326         };
10327         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;
10328         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10329
10330         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;
10331         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10332
10333         let dust_htlc_on_counterparty_tx: u64 = 25;
10334         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10335
10336         if on_holder_tx {
10337                 if dust_outbound_balance {
10338                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10339                         // Outbound dust balance: 4372 sats
10340                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10341                         for i in 0..dust_outbound_htlc_on_holder_tx {
10342                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10343                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10344                         }
10345                 } else {
10346                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10347                         // Inbound dust balance: 4372 sats
10348                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10349                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10350                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10351                         }
10352                 }
10353         } else {
10354                 if dust_outbound_balance {
10355                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10356                         // Outbound dust balance: 5000 sats
10357                         for i in 0..dust_htlc_on_counterparty_tx {
10358                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10359                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10360                         }
10361                 } else {
10362                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10363                         // Inbound dust balance: 5000 sats
10364                         for _ in 0..dust_htlc_on_counterparty_tx {
10365                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10366                         }
10367                 }
10368         }
10369
10370         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10371         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10372                 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 });
10373                 let mut config = UserConfig::default();
10374                 // With default dust exposure: 5000 sats
10375                 if on_holder_tx {
10376                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10377                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10378                         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)));
10379                 } else {
10380                         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)));
10381                 }
10382         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10383                 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 });
10384                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10385                 check_added_monitors!(nodes[1], 1);
10386                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10387                 assert_eq!(events.len(), 1);
10388                 let payment_event = SendEvent::from_event(events.remove(0));
10389                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10390                 // With default dust exposure: 5000 sats
10391                 if on_holder_tx {
10392                         // Outbound dust balance: 6399 sats
10393                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10394                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10395                         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);
10396                 } else {
10397                         // Outbound dust balance: 5200 sats
10398                         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);
10399                 }
10400         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10401                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10402                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10403                 {
10404                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10405                         *feerate_lock = *feerate_lock * 10;
10406                 }
10407                 nodes[0].node.timer_tick_occurred();
10408                 check_added_monitors!(nodes[0], 1);
10409                 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);
10410         }
10411
10412         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10413         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10414         added_monitors.clear();
10415 }
10416
10417 #[test]
10418 fn test_max_dust_htlc_exposure() {
10419         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10420         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10421         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10422         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10423         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10424         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10425         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10426         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10427         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10428         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10429         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10430         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10431 }
10432
10433 #[test]
10434 fn test_non_final_funding_tx() {
10435         let chanmon_cfgs = create_chanmon_cfgs(2);
10436         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10437         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10438         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10439
10440         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10441         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10442         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
10443         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10444         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
10445
10446         let best_height = nodes[0].node.best_block.read().unwrap().height();
10447
10448         let chan_id = *nodes[0].network_chan_count.borrow();
10449         let events = nodes[0].node.get_and_clear_pending_events();
10450         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: 0x1, witness: Witness::from_vec(vec!(vec!(1))) };
10451         assert_eq!(events.len(), 1);
10452         let mut tx = match events[0] {
10453                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10454                         // Timelock the transaction _beyond_ the best client height + 2.
10455                         Transaction { version: chan_id as i32, lock_time: best_height + 3, input: vec![input], output: vec![TxOut {
10456                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10457                         }]}
10458                 },
10459                 _ => panic!("Unexpected event"),
10460         };
10461         // Transaction should fail as it's evaluated as non-final for propagation.
10462         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10463                 Err(APIError::APIMisuseError { err }) => {
10464                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10465                 },
10466                 _ => panic!()
10467         }
10468
10469         // However, transaction should be accepted if it's in a +2 headroom from best block.
10470         tx.lock_time -= 1;
10471         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10472         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10473 }