Make all internal signatures accept LowerBoundedFeeEstimator
[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};
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 sync::{Arc, Mutex};
58
59 use ln::functional_test_utils::*;
60 use ln::chan_utils::CommitmentTransaction;
61
62 #[test]
63 fn test_insane_channel_opens() {
64         // Stand up a network of 2 nodes
65         use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
66         let mut cfg = UserConfig::default();
67         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
68         let chanmon_cfgs = create_chanmon_cfgs(2);
69         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
70         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
71         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
72
73         // Instantiate channel parameters where we push the maximum msats given our
74         // funding satoshis
75         let channel_value_sat = 31337; // same as funding satoshis
76         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
77         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
78
79         // Have node0 initiate a channel to node1 with aforementioned parameters
80         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
81
82         // Extract the channel open message from node0 to node1
83         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
84
85         // Test helper that asserts we get the correct error string given a mutator
86         // that supposedly makes the channel open message insane
87         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
88                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
89                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
90                 assert_eq!(msg_events.len(), 1);
91                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
92                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
93                         match action {
94                                 &ErrorAction::SendErrorMessage { .. } => {
95                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
96                                 },
97                                 _ => panic!("unexpected event!"),
98                         }
99                 } else { assert!(false); }
100         };
101
102         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
103
104         // Test all mutations that would make the channel open message insane
105         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 });
106         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 });
107
108         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
109
110         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 });
111
112         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
113
114         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 });
115
116         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 });
117
118         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
119
120         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
121 }
122
123 #[test]
124 fn test_funding_exceeds_no_wumbo_limit() {
125         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
126         // them.
127         use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
128         let chanmon_cfgs = create_chanmon_cfgs(2);
129         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
130         node_cfgs[1].features = InitFeatures::known().clear_wumbo();
131         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
132         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
133
134         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
135                 Err(APIError::APIMisuseError { err }) => {
136                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
137                 },
138                 _ => panic!()
139         }
140 }
141
142 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
143         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
144         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
145         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
146         // in normal testing, we test it explicitly here.
147         let chanmon_cfgs = create_chanmon_cfgs(2);
148         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
149         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
150         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
151
152         // Have node0 initiate a channel to node1 with aforementioned parameters
153         let mut push_amt = 100_000_000;
154         let feerate_per_kw = 253;
155         let opt_anchors = false;
156         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
157         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
158
159         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();
160         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
161         if !send_from_initiator {
162                 open_channel_message.channel_reserve_satoshis = 0;
163                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
164         }
165         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
166
167         // Extract the channel accept message from node1 to node0
168         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
169         if send_from_initiator {
170                 accept_channel_message.channel_reserve_satoshis = 0;
171                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
172         }
173         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
174         {
175                 let mut lock;
176                 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
177                 chan.holder_selected_channel_reserve_satoshis = 0;
178                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
179         }
180
181         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
182         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
183         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
184
185         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
186         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
187         if send_from_initiator {
188                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
189                         // Note that for outbound channels we have to consider the commitment tx fee and the
190                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
191                         // well as an additional HTLC.
192                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
193         } else {
194                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
195         }
196 }
197
198 #[test]
199 fn test_counterparty_no_reserve() {
200         do_test_counterparty_no_reserve(true);
201         do_test_counterparty_no_reserve(false);
202 }
203
204 #[test]
205 fn test_async_inbound_update_fee() {
206         let chanmon_cfgs = create_chanmon_cfgs(2);
207         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
208         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
209         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
210         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
211
212         // balancing
213         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
214
215         // A                                        B
216         // update_fee                            ->
217         // send (1) commitment_signed            -.
218         //                                       <- update_add_htlc/commitment_signed
219         // send (2) RAA (awaiting remote revoke) -.
220         // (1) commitment_signed is delivered    ->
221         //                                       .- send (3) RAA (awaiting remote revoke)
222         // (2) RAA is delivered                  ->
223         //                                       .- send (4) commitment_signed
224         //                                       <- (3) RAA is delivered
225         // send (5) commitment_signed            -.
226         //                                       <- (4) commitment_signed is delivered
227         // send (6) RAA                          -.
228         // (5) commitment_signed is delivered    ->
229         //                                       <- RAA
230         // (6) RAA is delivered                  ->
231
232         // First nodes[0] generates an update_fee
233         {
234                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
235                 *feerate_lock += 20;
236         }
237         nodes[0].node.timer_tick_occurred();
238         check_added_monitors!(nodes[0], 1);
239
240         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
241         assert_eq!(events_0.len(), 1);
242         let (update_msg, commitment_signed) = match events_0[0] { // (1)
243                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
244                         (update_fee.as_ref(), commitment_signed)
245                 },
246                 _ => panic!("Unexpected event"),
247         };
248
249         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
250
251         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
252         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
253         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
254         check_added_monitors!(nodes[1], 1);
255
256         let payment_event = {
257                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
258                 assert_eq!(events_1.len(), 1);
259                 SendEvent::from_event(events_1.remove(0))
260         };
261         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
262         assert_eq!(payment_event.msgs.len(), 1);
263
264         // ...now when the messages get delivered everyone should be happy
265         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
266         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
267         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
268         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
269         check_added_monitors!(nodes[0], 1);
270
271         // deliver(1), generate (3):
272         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
273         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
274         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
275         check_added_monitors!(nodes[1], 1);
276
277         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
278         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
279         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
280         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
281         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
282         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
283         assert!(bs_update.update_fee.is_none()); // (4)
284         check_added_monitors!(nodes[1], 1);
285
286         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
287         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
288         assert!(as_update.update_add_htlcs.is_empty()); // (5)
289         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
290         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
291         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
292         assert!(as_update.update_fee.is_none()); // (5)
293         check_added_monitors!(nodes[0], 1);
294
295         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
296         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
297         // only (6) so get_event_msg's assert(len == 1) passes
298         check_added_monitors!(nodes[0], 1);
299
300         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
301         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
302         check_added_monitors!(nodes[1], 1);
303
304         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
305         check_added_monitors!(nodes[0], 1);
306
307         let events_2 = nodes[0].node.get_and_clear_pending_events();
308         assert_eq!(events_2.len(), 1);
309         match events_2[0] {
310                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
311                 _ => panic!("Unexpected event"),
312         }
313
314         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
315         check_added_monitors!(nodes[1], 1);
316 }
317
318 #[test]
319 fn test_update_fee_unordered_raa() {
320         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
321         // crash in an earlier version of the update_fee patch)
322         let chanmon_cfgs = create_chanmon_cfgs(2);
323         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
324         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
325         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
326         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
327
328         // balancing
329         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
330
331         // First nodes[0] generates an update_fee
332         {
333                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
334                 *feerate_lock += 20;
335         }
336         nodes[0].node.timer_tick_occurred();
337         check_added_monitors!(nodes[0], 1);
338
339         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
340         assert_eq!(events_0.len(), 1);
341         let update_msg = match events_0[0] { // (1)
342                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
343                         update_fee.as_ref()
344                 },
345                 _ => panic!("Unexpected event"),
346         };
347
348         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
349
350         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
351         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
352         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
353         check_added_monitors!(nodes[1], 1);
354
355         let payment_event = {
356                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
357                 assert_eq!(events_1.len(), 1);
358                 SendEvent::from_event(events_1.remove(0))
359         };
360         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
361         assert_eq!(payment_event.msgs.len(), 1);
362
363         // ...now when the messages get delivered everyone should be happy
364         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
365         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
366         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
367         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
368         check_added_monitors!(nodes[0], 1);
369
370         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
371         check_added_monitors!(nodes[1], 1);
372
373         // We can't continue, sadly, because our (1) now has a bogus signature
374 }
375
376 #[test]
377 fn test_multi_flight_update_fee() {
378         let chanmon_cfgs = create_chanmon_cfgs(2);
379         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
380         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
381         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
382         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
383
384         // A                                        B
385         // update_fee/commitment_signed          ->
386         //                                       .- send (1) RAA and (2) commitment_signed
387         // update_fee (never committed)          ->
388         // (3) update_fee                        ->
389         // We have to manually generate the above update_fee, it is allowed by the protocol but we
390         // don't track which updates correspond to which revoke_and_ack responses so we're in
391         // AwaitingRAA mode and will not generate the update_fee yet.
392         //                                       <- (1) RAA delivered
393         // (3) is generated and send (4) CS      -.
394         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
395         // know the per_commitment_point to use for it.
396         //                                       <- (2) commitment_signed delivered
397         // revoke_and_ack                        ->
398         //                                          B should send no response here
399         // (4) commitment_signed delivered       ->
400         //                                       <- RAA/commitment_signed delivered
401         // revoke_and_ack                        ->
402
403         // First nodes[0] generates an update_fee
404         let initial_feerate;
405         {
406                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
407                 initial_feerate = *feerate_lock;
408                 *feerate_lock = initial_feerate + 20;
409         }
410         nodes[0].node.timer_tick_occurred();
411         check_added_monitors!(nodes[0], 1);
412
413         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
414         assert_eq!(events_0.len(), 1);
415         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
416                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
417                         (update_fee.as_ref().unwrap(), commitment_signed)
418                 },
419                 _ => panic!("Unexpected event"),
420         };
421
422         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
423         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
424         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
425         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
426         check_added_monitors!(nodes[1], 1);
427
428         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
429         // transaction:
430         {
431                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
432                 *feerate_lock = initial_feerate + 40;
433         }
434         nodes[0].node.timer_tick_occurred();
435         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
436         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
437
438         // Create the (3) update_fee message that nodes[0] will generate before it does...
439         let mut update_msg_2 = msgs::UpdateFee {
440                 channel_id: update_msg_1.channel_id.clone(),
441                 feerate_per_kw: (initial_feerate + 30) as u32,
442         };
443
444         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
445
446         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
447         // Deliver (3)
448         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
449
450         // Deliver (1), generating (3) and (4)
451         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
452         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
453         check_added_monitors!(nodes[0], 1);
454         assert!(as_second_update.update_add_htlcs.is_empty());
455         assert!(as_second_update.update_fulfill_htlcs.is_empty());
456         assert!(as_second_update.update_fail_htlcs.is_empty());
457         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
458         // Check that the update_fee newly generated matches what we delivered:
459         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
460         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
461
462         // Deliver (2) commitment_signed
463         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
464         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
465         check_added_monitors!(nodes[0], 1);
466         // No commitment_signed so get_event_msg's assert(len == 1) passes
467
468         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
469         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
470         check_added_monitors!(nodes[1], 1);
471
472         // Delever (4)
473         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
474         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
475         check_added_monitors!(nodes[1], 1);
476
477         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
478         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
479         check_added_monitors!(nodes[0], 1);
480
481         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
482         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
483         // No commitment_signed so get_event_msg's assert(len == 1) passes
484         check_added_monitors!(nodes[0], 1);
485
486         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
487         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
488         check_added_monitors!(nodes[1], 1);
489 }
490
491 fn do_test_sanity_on_in_flight_opens(steps: u8) {
492         // Previously, we had issues deserializing channels when we hadn't connected the first block
493         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
494         // serialization round-trips and simply do steps towards opening a channel and then drop the
495         // Node objects.
496
497         let chanmon_cfgs = create_chanmon_cfgs(2);
498         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
499         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
500         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
501
502         if steps & 0b1000_0000 != 0{
503                 let block = Block {
504                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
505                         txdata: vec![],
506                 };
507                 connect_block(&nodes[0], &block);
508                 connect_block(&nodes[1], &block);
509         }
510
511         if steps & 0x0f == 0 { return; }
512         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
513         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
514
515         if steps & 0x0f == 1 { return; }
516         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
517         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
518
519         if steps & 0x0f == 2 { return; }
520         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
521
522         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
523
524         if steps & 0x0f == 3 { return; }
525         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
526         check_added_monitors!(nodes[0], 0);
527         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
528
529         if steps & 0x0f == 4 { return; }
530         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
531         {
532                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
533                 assert_eq!(added_monitors.len(), 1);
534                 assert_eq!(added_monitors[0].0, funding_output);
535                 added_monitors.clear();
536         }
537         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
538
539         if steps & 0x0f == 5 { return; }
540         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
541         {
542                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
543                 assert_eq!(added_monitors.len(), 1);
544                 assert_eq!(added_monitors[0].0, funding_output);
545                 added_monitors.clear();
546         }
547
548         let events_4 = nodes[0].node.get_and_clear_pending_events();
549         assert_eq!(events_4.len(), 0);
550
551         if steps & 0x0f == 6 { return; }
552         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
553
554         if steps & 0x0f == 7 { return; }
555         confirm_transaction_at(&nodes[0], &tx, 2);
556         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
557         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
558 }
559
560 #[test]
561 fn test_sanity_on_in_flight_opens() {
562         do_test_sanity_on_in_flight_opens(0);
563         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
564         do_test_sanity_on_in_flight_opens(1);
565         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
566         do_test_sanity_on_in_flight_opens(2);
567         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
568         do_test_sanity_on_in_flight_opens(3);
569         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
570         do_test_sanity_on_in_flight_opens(4);
571         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
572         do_test_sanity_on_in_flight_opens(5);
573         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
574         do_test_sanity_on_in_flight_opens(6);
575         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
576         do_test_sanity_on_in_flight_opens(7);
577         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
578         do_test_sanity_on_in_flight_opens(8);
579         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
580 }
581
582 #[test]
583 fn test_update_fee_vanilla() {
584         let chanmon_cfgs = create_chanmon_cfgs(2);
585         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
586         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
587         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
588         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
589
590         {
591                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
592                 *feerate_lock += 25;
593         }
594         nodes[0].node.timer_tick_occurred();
595         check_added_monitors!(nodes[0], 1);
596
597         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
598         assert_eq!(events_0.len(), 1);
599         let (update_msg, commitment_signed) = match events_0[0] {
600                         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 } } => {
601                         (update_fee.as_ref(), commitment_signed)
602                 },
603                 _ => panic!("Unexpected event"),
604         };
605         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
606
607         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
608         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
609         check_added_monitors!(nodes[1], 1);
610
611         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
612         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
613         check_added_monitors!(nodes[0], 1);
614
615         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
616         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
617         // No commitment_signed so get_event_msg's assert(len == 1) passes
618         check_added_monitors!(nodes[0], 1);
619
620         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
621         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
622         check_added_monitors!(nodes[1], 1);
623 }
624
625 #[test]
626 fn test_update_fee_that_funder_cannot_afford() {
627         let chanmon_cfgs = create_chanmon_cfgs(2);
628         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
629         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
630         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
631         let channel_value = 5000;
632         let push_sats = 700;
633         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
634         let channel_id = chan.2;
635         let secp_ctx = Secp256k1::new();
636         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
637
638         let opt_anchors = false;
639
640         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
641         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
642         // calculate two different feerates here - the expected local limit as well as the expected
643         // remote limit.
644         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;
645         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
646         {
647                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
648                 *feerate_lock = feerate;
649         }
650         nodes[0].node.timer_tick_occurred();
651         check_added_monitors!(nodes[0], 1);
652         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
653
654         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
655
656         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
657
658         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
659         {
660                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
661
662                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
663                 assert_eq!(commitment_tx.output.len(), 2);
664                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
665                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
666                 actual_fee = channel_value - actual_fee;
667                 assert_eq!(total_fee, actual_fee);
668         }
669
670         {
671                 // Increment the feerate by a small constant, accounting for rounding errors
672                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
673                 *feerate_lock += 4;
674         }
675         nodes[0].node.timer_tick_occurred();
676         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
677         check_added_monitors!(nodes[0], 0);
678
679         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
680
681         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
682         // needed to sign the new commitment tx and (2) sign the new commitment tx.
683         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
684                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
685                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
686                 let chan_signer = local_chan.get_signer();
687                 let pubkeys = chan_signer.pubkeys();
688                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
689                  pubkeys.funding_pubkey)
690         };
691         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
692                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
693                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
694                 let chan_signer = remote_chan.get_signer();
695                 let pubkeys = chan_signer.pubkeys();
696                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
697                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
698                  pubkeys.funding_pubkey)
699         };
700
701         // Assemble the set of keys we can use for signatures for our commitment_signed message.
702         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
703                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
704
705         let res = {
706                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
707                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
708                 let local_chan_signer = local_chan.get_signer();
709                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
710                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
711                         INITIAL_COMMITMENT_NUMBER - 1,
712                         push_sats,
713                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
714                         opt_anchors, local_funding, remote_funding,
715                         commit_tx_keys.clone(),
716                         non_buffer_feerate + 4,
717                         &mut htlcs,
718                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
719                 );
720                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
721         };
722
723         let commit_signed_msg = msgs::CommitmentSigned {
724                 channel_id: chan.2,
725                 signature: res.0,
726                 htlc_signatures: res.1
727         };
728
729         let update_fee = msgs::UpdateFee {
730                 channel_id: chan.2,
731                 feerate_per_kw: non_buffer_feerate + 4,
732         };
733
734         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
735
736         //While producing the commitment_signed response after handling a received update_fee request the
737         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
738         //Should produce and error.
739         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
740         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
741         check_added_monitors!(nodes[1], 1);
742         check_closed_broadcast!(nodes[1], true);
743         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
744 }
745
746 #[test]
747 fn test_update_fee_with_fundee_update_add_htlc() {
748         let chanmon_cfgs = create_chanmon_cfgs(2);
749         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
750         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
751         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
752         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
753
754         // balancing
755         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
756
757         {
758                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
759                 *feerate_lock += 20;
760         }
761         nodes[0].node.timer_tick_occurred();
762         check_added_monitors!(nodes[0], 1);
763
764         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
765         assert_eq!(events_0.len(), 1);
766         let (update_msg, commitment_signed) = match events_0[0] {
767                         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 } } => {
768                         (update_fee.as_ref(), commitment_signed)
769                 },
770                 _ => panic!("Unexpected event"),
771         };
772         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
773         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
774         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
775         check_added_monitors!(nodes[1], 1);
776
777         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
778
779         // nothing happens since node[1] is in AwaitingRemoteRevoke
780         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
781         {
782                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
783                 assert_eq!(added_monitors.len(), 0);
784                 added_monitors.clear();
785         }
786         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
787         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
788         // node[1] has nothing to do
789
790         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
791         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
792         check_added_monitors!(nodes[0], 1);
793
794         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
795         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
796         // No commitment_signed so get_event_msg's assert(len == 1) passes
797         check_added_monitors!(nodes[0], 1);
798         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
799         check_added_monitors!(nodes[1], 1);
800         // AwaitingRemoteRevoke ends here
801
802         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
803         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
804         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
805         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
806         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
807         assert_eq!(commitment_update.update_fee.is_none(), true);
808
809         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
810         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
811         check_added_monitors!(nodes[0], 1);
812         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
813
814         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
815         check_added_monitors!(nodes[1], 1);
816         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
817
818         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
819         check_added_monitors!(nodes[1], 1);
820         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
821         // No commitment_signed so get_event_msg's assert(len == 1) passes
822
823         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
824         check_added_monitors!(nodes[0], 1);
825         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
826
827         expect_pending_htlcs_forwardable!(nodes[0]);
828
829         let events = nodes[0].node.get_and_clear_pending_events();
830         assert_eq!(events.len(), 1);
831         match events[0] {
832                 Event::PaymentReceived { .. } => { },
833                 _ => panic!("Unexpected event"),
834         };
835
836         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
837
838         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
839         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
840         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
841         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
842         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
843 }
844
845 #[test]
846 fn test_update_fee() {
847         let chanmon_cfgs = create_chanmon_cfgs(2);
848         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
849         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
850         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
851         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
852         let channel_id = chan.2;
853
854         // A                                        B
855         // (1) update_fee/commitment_signed      ->
856         //                                       <- (2) revoke_and_ack
857         //                                       .- send (3) commitment_signed
858         // (4) update_fee/commitment_signed      ->
859         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
860         //                                       <- (3) commitment_signed delivered
861         // send (6) revoke_and_ack               -.
862         //                                       <- (5) deliver revoke_and_ack
863         // (6) deliver revoke_and_ack            ->
864         //                                       .- send (7) commitment_signed in response to (4)
865         //                                       <- (7) deliver commitment_signed
866         // revoke_and_ack                        ->
867
868         // Create and deliver (1)...
869         let feerate;
870         {
871                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
872                 feerate = *feerate_lock;
873                 *feerate_lock = feerate + 20;
874         }
875         nodes[0].node.timer_tick_occurred();
876         check_added_monitors!(nodes[0], 1);
877
878         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
879         assert_eq!(events_0.len(), 1);
880         let (update_msg, commitment_signed) = match events_0[0] {
881                         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 } } => {
882                         (update_fee.as_ref(), commitment_signed)
883                 },
884                 _ => panic!("Unexpected event"),
885         };
886         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
887
888         // Generate (2) and (3):
889         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
890         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
891         check_added_monitors!(nodes[1], 1);
892
893         // Deliver (2):
894         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
895         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
896         check_added_monitors!(nodes[0], 1);
897
898         // Create and deliver (4)...
899         {
900                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
901                 *feerate_lock = feerate + 30;
902         }
903         nodes[0].node.timer_tick_occurred();
904         check_added_monitors!(nodes[0], 1);
905         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
906         assert_eq!(events_0.len(), 1);
907         let (update_msg, commitment_signed) = match events_0[0] {
908                         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 } } => {
909                         (update_fee.as_ref(), commitment_signed)
910                 },
911                 _ => panic!("Unexpected event"),
912         };
913
914         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
915         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
916         check_added_monitors!(nodes[1], 1);
917         // ... creating (5)
918         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
919         // No commitment_signed so get_event_msg's assert(len == 1) passes
920
921         // Handle (3), creating (6):
922         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
923         check_added_monitors!(nodes[0], 1);
924         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
925         // No commitment_signed so get_event_msg's assert(len == 1) passes
926
927         // Deliver (5):
928         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
929         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
930         check_added_monitors!(nodes[0], 1);
931
932         // Deliver (6), creating (7):
933         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
934         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
935         assert!(commitment_update.update_add_htlcs.is_empty());
936         assert!(commitment_update.update_fulfill_htlcs.is_empty());
937         assert!(commitment_update.update_fail_htlcs.is_empty());
938         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
939         assert!(commitment_update.update_fee.is_none());
940         check_added_monitors!(nodes[1], 1);
941
942         // Deliver (7)
943         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
944         check_added_monitors!(nodes[0], 1);
945         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
946         // No commitment_signed so get_event_msg's assert(len == 1) passes
947
948         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
949         check_added_monitors!(nodes[1], 1);
950         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
951
952         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
953         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
954         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
955         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
956         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
957 }
958
959 #[test]
960 fn fake_network_test() {
961         // Simple test which builds a network of ChannelManagers, connects them to each other, and
962         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
963         let chanmon_cfgs = create_chanmon_cfgs(4);
964         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
965         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
966         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
967
968         // Create some initial channels
969         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
970         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
971         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
972
973         // Rebalance the network a bit by relaying one payment through all the channels...
974         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
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
979         // Send some more payments
980         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
981         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
982         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
983
984         // Test failure packets
985         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
986         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
987
988         // Add a new channel that skips 3
989         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
990
991         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
992         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
993         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
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
999         // Do some rebalance loop payments, simultaneously
1000         let mut hops = Vec::with_capacity(3);
1001         hops.push(RouteHop {
1002                 pubkey: nodes[2].node.get_our_node_id(),
1003                 node_features: NodeFeatures::empty(),
1004                 short_channel_id: chan_2.0.contents.short_channel_id,
1005                 channel_features: ChannelFeatures::empty(),
1006                 fee_msat: 0,
1007                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1008         });
1009         hops.push(RouteHop {
1010                 pubkey: nodes[3].node.get_our_node_id(),
1011                 node_features: NodeFeatures::empty(),
1012                 short_channel_id: chan_3.0.contents.short_channel_id,
1013                 channel_features: ChannelFeatures::empty(),
1014                 fee_msat: 0,
1015                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1016         });
1017         hops.push(RouteHop {
1018                 pubkey: nodes[1].node.get_our_node_id(),
1019                 node_features: NodeFeatures::known(),
1020                 short_channel_id: chan_4.0.contents.short_channel_id,
1021                 channel_features: ChannelFeatures::known(),
1022                 fee_msat: 1000000,
1023                 cltv_expiry_delta: TEST_FINAL_CLTV,
1024         });
1025         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;
1026         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;
1027         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;
1028
1029         let mut hops = Vec::with_capacity(3);
1030         hops.push(RouteHop {
1031                 pubkey: nodes[3].node.get_our_node_id(),
1032                 node_features: NodeFeatures::empty(),
1033                 short_channel_id: chan_4.0.contents.short_channel_id,
1034                 channel_features: ChannelFeatures::empty(),
1035                 fee_msat: 0,
1036                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1037         });
1038         hops.push(RouteHop {
1039                 pubkey: nodes[2].node.get_our_node_id(),
1040                 node_features: NodeFeatures::empty(),
1041                 short_channel_id: chan_3.0.contents.short_channel_id,
1042                 channel_features: ChannelFeatures::empty(),
1043                 fee_msat: 0,
1044                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1045         });
1046         hops.push(RouteHop {
1047                 pubkey: nodes[1].node.get_our_node_id(),
1048                 node_features: NodeFeatures::known(),
1049                 short_channel_id: chan_2.0.contents.short_channel_id,
1050                 channel_features: ChannelFeatures::known(),
1051                 fee_msat: 1000000,
1052                 cltv_expiry_delta: TEST_FINAL_CLTV,
1053         });
1054         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;
1055         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;
1056         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;
1057
1058         // Claim the rebalances...
1059         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1060         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1061
1062         // Add a duplicate new channel from 2 to 4
1063         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1064
1065         // Send some payments across both channels
1066         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1067         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1068         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1069
1070
1071         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1072         let events = nodes[0].node.get_and_clear_pending_msg_events();
1073         assert_eq!(events.len(), 0);
1074         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);
1075
1076         //TODO: Test that routes work again here as we've been notified that the channel is full
1077
1078         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1079         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1080         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1081
1082         // Close down the channels...
1083         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1084         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1085         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1086         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1087         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1088         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1089         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1090         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1091         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1092         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1093         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1094         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1095         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1096         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1097         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1098 }
1099
1100 #[test]
1101 fn holding_cell_htlc_counting() {
1102         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1103         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1104         // commitment dance rounds.
1105         let chanmon_cfgs = create_chanmon_cfgs(3);
1106         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1107         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1108         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1109         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1110         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1111
1112         let mut payments = Vec::new();
1113         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1114                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1115                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1116                 payments.push((payment_preimage, payment_hash));
1117         }
1118         check_added_monitors!(nodes[1], 1);
1119
1120         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1121         assert_eq!(events.len(), 1);
1122         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1123         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1124
1125         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1126         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1127         // another HTLC.
1128         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1129         {
1130                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1131                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1132                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1133                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1134         }
1135
1136         // This should also be true if we try to forward a payment.
1137         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1138         {
1139                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1140                 check_added_monitors!(nodes[0], 1);
1141         }
1142
1143         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1144         assert_eq!(events.len(), 1);
1145         let payment_event = SendEvent::from_event(events.pop().unwrap());
1146         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1147
1148         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1149         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1150         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1151         // fails), the second will process the resulting failure and fail the HTLC backward.
1152         expect_pending_htlcs_forwardable!(nodes[1]);
1153         expect_pending_htlcs_forwardable!(nodes[1]);
1154         check_added_monitors!(nodes[1], 1);
1155
1156         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1157         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1158         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1159
1160         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1161
1162         // Now forward all the pending HTLCs and claim them back
1163         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1164         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1165         check_added_monitors!(nodes[2], 1);
1166
1167         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1168         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1169         check_added_monitors!(nodes[1], 1);
1170         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1171
1172         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1173         check_added_monitors!(nodes[1], 1);
1174         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1175
1176         for ref update in as_updates.update_add_htlcs.iter() {
1177                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1178         }
1179         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1180         check_added_monitors!(nodes[2], 1);
1181         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1182         check_added_monitors!(nodes[2], 1);
1183         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1184
1185         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1186         check_added_monitors!(nodes[1], 1);
1187         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1188         check_added_monitors!(nodes[1], 1);
1189         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1190
1191         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1192         check_added_monitors!(nodes[2], 1);
1193
1194         expect_pending_htlcs_forwardable!(nodes[2]);
1195
1196         let events = nodes[2].node.get_and_clear_pending_events();
1197         assert_eq!(events.len(), payments.len());
1198         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1199                 match event {
1200                         &Event::PaymentReceived { ref payment_hash, .. } => {
1201                                 assert_eq!(*payment_hash, *hash);
1202                         },
1203                         _ => panic!("Unexpected event"),
1204                 };
1205         }
1206
1207         for (preimage, _) in payments.drain(..) {
1208                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1209         }
1210
1211         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1212 }
1213
1214 #[test]
1215 fn duplicate_htlc_test() {
1216         // Test that we accept duplicate payment_hash HTLCs across the network and that
1217         // claiming/failing them are all separate and don't affect each other
1218         let chanmon_cfgs = create_chanmon_cfgs(6);
1219         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1220         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1221         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1222
1223         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1224         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1225         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1226         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1227         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1228         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1229
1230         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1231
1232         *nodes[0].network_payment_count.borrow_mut() -= 1;
1233         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1234
1235         *nodes[0].network_payment_count.borrow_mut() -= 1;
1236         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1237
1238         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1239         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1240         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1241 }
1242
1243 #[test]
1244 fn test_duplicate_htlc_different_direction_onchain() {
1245         // Test that ChannelMonitor doesn't generate 2 preimage txn
1246         // when we have 2 HTLCs with same preimage that go across a node
1247         // in opposite directions, even with the same payment secret.
1248         let chanmon_cfgs = create_chanmon_cfgs(2);
1249         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1250         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1251         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1252
1253         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1254
1255         // balancing
1256         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1257
1258         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1259
1260         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1261         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1262         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1263
1264         // Provide preimage to node 0 by claiming payment
1265         nodes[0].node.claim_funds(payment_preimage);
1266         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1267         check_added_monitors!(nodes[0], 1);
1268
1269         // Broadcast node 1 commitment txn
1270         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1271
1272         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1273         let mut has_both_htlcs = 0; // check htlcs match ones committed
1274         for outp in remote_txn[0].output.iter() {
1275                 if outp.value == 800_000 / 1000 {
1276                         has_both_htlcs += 1;
1277                 } else if outp.value == 900_000 / 1000 {
1278                         has_both_htlcs += 1;
1279                 }
1280         }
1281         assert_eq!(has_both_htlcs, 2);
1282
1283         mine_transaction(&nodes[0], &remote_txn[0]);
1284         check_added_monitors!(nodes[0], 1);
1285         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1286         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1287
1288         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1289         assert_eq!(claim_txn.len(), 8);
1290
1291         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1292
1293         check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1294         check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1295
1296         let bump_tx = if claim_txn[1] == claim_txn[4] {
1297                 assert_eq!(claim_txn[1], claim_txn[4]);
1298                 assert_eq!(claim_txn[2], claim_txn[5]);
1299
1300                 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1301
1302                 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1303                 &claim_txn[3]
1304         } else {
1305                 assert_eq!(claim_txn[1], claim_txn[3]);
1306                 assert_eq!(claim_txn[2], claim_txn[4]);
1307
1308                 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1309
1310                 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1311
1312                 &claim_txn[7]
1313         };
1314
1315         assert_eq!(claim_txn[0].input.len(), 1);
1316         assert_eq!(bump_tx.input.len(), 1);
1317         assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1318
1319         assert_eq!(claim_txn[0].input.len(), 1);
1320         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1321         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1322
1323         assert_eq!(claim_txn[6].input.len(), 1);
1324         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1325         check_spends!(claim_txn[6], remote_txn[0]);
1326         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1327
1328         let events = nodes[0].node.get_and_clear_pending_msg_events();
1329         assert_eq!(events.len(), 3);
1330         for e in events {
1331                 match e {
1332                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1333                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1334                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1335                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1336                         },
1337                         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, .. } } => {
1338                                 assert!(update_add_htlcs.is_empty());
1339                                 assert!(update_fail_htlcs.is_empty());
1340                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1341                                 assert!(update_fail_malformed_htlcs.is_empty());
1342                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1343                         },
1344                         _ => panic!("Unexpected event"),
1345                 }
1346         }
1347 }
1348
1349 #[test]
1350 fn test_basic_channel_reserve() {
1351         let chanmon_cfgs = create_chanmon_cfgs(2);
1352         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1353         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1354         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1355         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1356
1357         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1358         let channel_reserve = chan_stat.channel_reserve_msat;
1359
1360         // The 2* and +1 are for the fee spike reserve.
1361         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1362         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1363         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1364         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1365         match err {
1366                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1367                         match &fails[0] {
1368                                 &APIError::ChannelUnavailable{ref err} =>
1369                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1370                                 _ => panic!("Unexpected error variant"),
1371                         }
1372                 },
1373                 _ => panic!("Unexpected error variant"),
1374         }
1375         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1376         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);
1377
1378         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1379 }
1380
1381 #[test]
1382 fn test_fee_spike_violation_fails_htlc() {
1383         let chanmon_cfgs = create_chanmon_cfgs(2);
1384         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1385         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1386         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1387         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1388
1389         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1390         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1391         let secp_ctx = Secp256k1::new();
1392         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1393
1394         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1395
1396         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1397         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1398         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1399         let msg = msgs::UpdateAddHTLC {
1400                 channel_id: chan.2,
1401                 htlc_id: 0,
1402                 amount_msat: htlc_msat,
1403                 payment_hash: payment_hash,
1404                 cltv_expiry: htlc_cltv,
1405                 onion_routing_packet: onion_packet,
1406         };
1407
1408         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1409
1410         // Now manually create the commitment_signed message corresponding to the update_add
1411         // nodes[0] just sent. In the code for construction of this message, "local" refers
1412         // to the sender of the message, and "remote" refers to the receiver.
1413
1414         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1415
1416         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1417
1418         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1419         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1420         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1421                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1422                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1423                 let chan_signer = local_chan.get_signer();
1424                 // Make the signer believe we validated another commitment, so we can release the secret
1425                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1426
1427                 let pubkeys = chan_signer.pubkeys();
1428                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1429                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1430                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1431                  chan_signer.pubkeys().funding_pubkey)
1432         };
1433         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1434                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1435                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1436                 let chan_signer = remote_chan.get_signer();
1437                 let pubkeys = chan_signer.pubkeys();
1438                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1439                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1440                  chan_signer.pubkeys().funding_pubkey)
1441         };
1442
1443         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1444         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1445                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1446
1447         // Build the remote commitment transaction so we can sign it, and then later use the
1448         // signature for the commitment_signed message.
1449         let local_chan_balance = 1313;
1450
1451         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1452                 offered: false,
1453                 amount_msat: 3460001,
1454                 cltv_expiry: htlc_cltv,
1455                 payment_hash,
1456                 transaction_output_index: Some(1),
1457         };
1458
1459         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1460
1461         let res = {
1462                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1463                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1464                 let local_chan_signer = local_chan.get_signer();
1465                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1466                         commitment_number,
1467                         95000,
1468                         local_chan_balance,
1469                         local_chan.opt_anchors(), local_funding, remote_funding,
1470                         commit_tx_keys.clone(),
1471                         feerate_per_kw,
1472                         &mut vec![(accepted_htlc_info, ())],
1473                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1474                 );
1475                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1476         };
1477
1478         let commit_signed_msg = msgs::CommitmentSigned {
1479                 channel_id: chan.2,
1480                 signature: res.0,
1481                 htlc_signatures: res.1
1482         };
1483
1484         // Send the commitment_signed message to the nodes[1].
1485         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1486         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1487
1488         // Send the RAA to nodes[1].
1489         let raa_msg = msgs::RevokeAndACK {
1490                 channel_id: chan.2,
1491                 per_commitment_secret: local_secret,
1492                 next_per_commitment_point: next_local_point
1493         };
1494         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1495
1496         let events = nodes[1].node.get_and_clear_pending_msg_events();
1497         assert_eq!(events.len(), 1);
1498         // Make sure the HTLC failed in the way we expect.
1499         match events[0] {
1500                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1501                         assert_eq!(update_fail_htlcs.len(), 1);
1502                         update_fail_htlcs[0].clone()
1503                 },
1504                 _ => panic!("Unexpected event"),
1505         };
1506         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1507                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1508
1509         check_added_monitors!(nodes[1], 2);
1510 }
1511
1512 #[test]
1513 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1514         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1515         // Set the fee rate for the channel very high, to the point where the fundee
1516         // sending any above-dust amount would result in a channel reserve violation.
1517         // In this test we check that we would be prevented from sending an HTLC in
1518         // this situation.
1519         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1520         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1521         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1522         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1523
1524         let opt_anchors = false;
1525
1526         let mut push_amt = 100_000_000;
1527         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1528         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1529
1530         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1531
1532         // Sending exactly enough to hit the reserve amount should be accepted
1533         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1534                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1535         }
1536
1537         // However one more HTLC should be significantly over the reserve amount and fail.
1538         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1539         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1540                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1541         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1542         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);
1543 }
1544
1545 #[test]
1546 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1547         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1548         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1549         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1550         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1551         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1552
1553         let opt_anchors = false;
1554
1555         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1556         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1557         // transaction fee with 0 HTLCs (183 sats)).
1558         let mut push_amt = 100_000_000;
1559         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1560         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1561         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1562
1563         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1564         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1565                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1566         }
1567
1568         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1569         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1570         let secp_ctx = Secp256k1::new();
1571         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1572         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1573         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1574         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1575         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1576         let msg = msgs::UpdateAddHTLC {
1577                 channel_id: chan.2,
1578                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1579                 amount_msat: htlc_msat,
1580                 payment_hash: payment_hash,
1581                 cltv_expiry: htlc_cltv,
1582                 onion_routing_packet: onion_packet,
1583         };
1584
1585         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1586         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1587         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);
1588         assert_eq!(nodes[0].node.list_channels().len(), 0);
1589         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1590         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1591         check_added_monitors!(nodes[0], 1);
1592         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() });
1593 }
1594
1595 #[test]
1596 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1597         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1598         // calculating our commitment transaction fee (this was previously broken).
1599         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1600         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1601
1602         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1603         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1604         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1605
1606         let opt_anchors = false;
1607
1608         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1609         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1610         // transaction fee with 0 HTLCs (183 sats)).
1611         let mut push_amt = 100_000_000;
1612         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1613         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1614         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1615
1616         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1617                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1618         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1619         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1620         // commitment transaction fee.
1621         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1622
1623         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1624         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1625                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1626         }
1627
1628         // One more than the dust amt should fail, however.
1629         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1630         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1631                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1632 }
1633
1634 #[test]
1635 fn test_chan_init_feerate_unaffordability() {
1636         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1637         // channel reserve and feerate requirements.
1638         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1639         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1640         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1641         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1642         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1643
1644         let opt_anchors = false;
1645
1646         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1647         // HTLC.
1648         let mut push_amt = 100_000_000;
1649         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1650         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1651                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1652
1653         // During open, we don't have a "counterparty channel reserve" to check against, so that
1654         // requirement only comes into play on the open_channel handling side.
1655         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1656         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1657         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1658         open_channel_msg.push_msat += 1;
1659         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1660
1661         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1662         assert_eq!(msg_events.len(), 1);
1663         match msg_events[0] {
1664                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1665                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1666                 },
1667                 _ => panic!("Unexpected event"),
1668         }
1669 }
1670
1671 #[test]
1672 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1673         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1674         // calculating our counterparty's commitment transaction fee (this was previously broken).
1675         let chanmon_cfgs = create_chanmon_cfgs(2);
1676         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1677         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1678         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1679         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1680
1681         let payment_amt = 46000; // Dust amount
1682         // In the previous code, these first four payments would succeed.
1683         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
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
1688         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1689         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
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
1695         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1696         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1697         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1698         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1699 }
1700
1701 #[test]
1702 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1703         let chanmon_cfgs = create_chanmon_cfgs(3);
1704         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1705         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1706         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1707         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1708         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1709
1710         let feemsat = 239;
1711         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1712         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1713         let feerate = get_feerate!(nodes[0], chan.2);
1714         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1715
1716         // Add a 2* and +1 for the fee spike reserve.
1717         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1718         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;
1719         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1720
1721         // Add a pending HTLC.
1722         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1723         let payment_event_1 = {
1724                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1725                 check_added_monitors!(nodes[0], 1);
1726
1727                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1728                 assert_eq!(events.len(), 1);
1729                 SendEvent::from_event(events.remove(0))
1730         };
1731         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1732
1733         // Attempt to trigger a channel reserve violation --> payment failure.
1734         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1735         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;
1736         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1737         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1738
1739         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1740         let secp_ctx = Secp256k1::new();
1741         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1742         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1743         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1744         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1745         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1746         let msg = msgs::UpdateAddHTLC {
1747                 channel_id: chan.2,
1748                 htlc_id: 1,
1749                 amount_msat: htlc_msat + 1,
1750                 payment_hash: our_payment_hash_1,
1751                 cltv_expiry: htlc_cltv,
1752                 onion_routing_packet: onion_packet,
1753         };
1754
1755         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1756         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1757         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1758         assert_eq!(nodes[1].node.list_channels().len(), 1);
1759         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1760         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1761         check_added_monitors!(nodes[1], 1);
1762         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1763 }
1764
1765 #[test]
1766 fn test_inbound_outbound_capacity_is_not_zero() {
1767         let chanmon_cfgs = create_chanmon_cfgs(2);
1768         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1769         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1770         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1771         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1772         let channels0 = node_chanmgrs[0].list_channels();
1773         let channels1 = node_chanmgrs[1].list_channels();
1774         assert_eq!(channels0.len(), 1);
1775         assert_eq!(channels1.len(), 1);
1776
1777         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1778         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1779         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1780
1781         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1782         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1783 }
1784
1785 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1786         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1787 }
1788
1789 #[test]
1790 fn test_channel_reserve_holding_cell_htlcs() {
1791         let chanmon_cfgs = create_chanmon_cfgs(3);
1792         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1793         // When this test was written, the default base fee floated based on the HTLC count.
1794         // It is now fixed, so we simply set the fee to the expected value here.
1795         let mut config = test_default_channel_config();
1796         config.channel_config.forwarding_fee_base_msat = 239;
1797         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1798         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1799         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1800         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1801
1802         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1803         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1804
1805         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1806         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1807
1808         macro_rules! expect_forward {
1809                 ($node: expr) => {{
1810                         let mut events = $node.node.get_and_clear_pending_msg_events();
1811                         assert_eq!(events.len(), 1);
1812                         check_added_monitors!($node, 1);
1813                         let payment_event = SendEvent::from_event(events.remove(0));
1814                         payment_event
1815                 }}
1816         }
1817
1818         let feemsat = 239; // set above
1819         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1820         let feerate = get_feerate!(nodes[0], chan_1.2);
1821         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1822
1823         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1824
1825         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1826         {
1827                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1828                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1829                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1830                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1831                         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)));
1832                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1833                 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);
1834         }
1835
1836         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1837         // nodes[0]'s wealth
1838         loop {
1839                 let amt_msat = recv_value_0 + total_fee_msat;
1840                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1841                 // Also, ensure that each payment has enough to be over the dust limit to
1842                 // ensure it'll be included in each commit tx fee calculation.
1843                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1844                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1845                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1846                         break;
1847                 }
1848                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1849
1850                 let (stat01_, stat11_, stat12_, stat22_) = (
1851                         get_channel_value_stat!(nodes[0], chan_1.2),
1852                         get_channel_value_stat!(nodes[1], chan_1.2),
1853                         get_channel_value_stat!(nodes[1], chan_2.2),
1854                         get_channel_value_stat!(nodes[2], chan_2.2),
1855                 );
1856
1857                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1858                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1859                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1860                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1861                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1862         }
1863
1864         // adding pending output.
1865         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1866         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1867         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1868         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1869         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1870         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1871         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1872         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1873         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1874         // policy.
1875         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1876         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1877         let amt_msat_1 = recv_value_1 + total_fee_msat;
1878
1879         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);
1880         let payment_event_1 = {
1881                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1882                 check_added_monitors!(nodes[0], 1);
1883
1884                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1885                 assert_eq!(events.len(), 1);
1886                 SendEvent::from_event(events.remove(0))
1887         };
1888         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1889
1890         // channel reserve test with htlc pending output > 0
1891         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1892         {
1893                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1894                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1895                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1896                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1897         }
1898
1899         // split the rest to test holding cell
1900         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1901         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1902         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1903         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1904         {
1905                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1906                 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);
1907         }
1908
1909         // now see if they go through on both sides
1910         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);
1911         // but this will stuck in the holding cell
1912         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1913         check_added_monitors!(nodes[0], 0);
1914         let events = nodes[0].node.get_and_clear_pending_events();
1915         assert_eq!(events.len(), 0);
1916
1917         // test with outbound holding cell amount > 0
1918         {
1919                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1920                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1921                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1922                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1923                 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);
1924         }
1925
1926         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);
1927         // this will also stuck in the holding cell
1928         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1929         check_added_monitors!(nodes[0], 0);
1930         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1931         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1932
1933         // flush the pending htlc
1934         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1935         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1936         check_added_monitors!(nodes[1], 1);
1937
1938         // the pending htlc should be promoted to committed
1939         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1940         check_added_monitors!(nodes[0], 1);
1941         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1942
1943         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1944         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1945         // No commitment_signed so get_event_msg's assert(len == 1) passes
1946         check_added_monitors!(nodes[0], 1);
1947
1948         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1949         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1950         check_added_monitors!(nodes[1], 1);
1951
1952         expect_pending_htlcs_forwardable!(nodes[1]);
1953
1954         let ref payment_event_11 = expect_forward!(nodes[1]);
1955         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1956         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1957
1958         expect_pending_htlcs_forwardable!(nodes[2]);
1959         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1960
1961         // flush the htlcs in the holding cell
1962         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1963         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1964         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1965         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1966         expect_pending_htlcs_forwardable!(nodes[1]);
1967
1968         let ref payment_event_3 = expect_forward!(nodes[1]);
1969         assert_eq!(payment_event_3.msgs.len(), 2);
1970         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1971         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1972
1973         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1974         expect_pending_htlcs_forwardable!(nodes[2]);
1975
1976         let events = nodes[2].node.get_and_clear_pending_events();
1977         assert_eq!(events.len(), 2);
1978         match events[0] {
1979                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1980                         assert_eq!(our_payment_hash_21, *payment_hash);
1981                         assert_eq!(recv_value_21, amount_msat);
1982                         match &purpose {
1983                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1984                                         assert!(payment_preimage.is_none());
1985                                         assert_eq!(our_payment_secret_21, *payment_secret);
1986                                 },
1987                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1988                         }
1989                 },
1990                 _ => panic!("Unexpected event"),
1991         }
1992         match events[1] {
1993                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1994                         assert_eq!(our_payment_hash_22, *payment_hash);
1995                         assert_eq!(recv_value_22, amount_msat);
1996                         match &purpose {
1997                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1998                                         assert!(payment_preimage.is_none());
1999                                         assert_eq!(our_payment_secret_22, *payment_secret);
2000                                 },
2001                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2002                         }
2003                 },
2004                 _ => panic!("Unexpected event"),
2005         }
2006
2007         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2008         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2009         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2010
2011         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2012         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2013         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2014
2015         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2016         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);
2017         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2018         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2019         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2020
2021         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2022         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2023 }
2024
2025 #[test]
2026 fn channel_reserve_in_flight_removes() {
2027         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2028         // can send to its counterparty, but due to update ordering, the other side may not yet have
2029         // considered those HTLCs fully removed.
2030         // This tests that we don't count HTLCs which will not be included in the next remote
2031         // commitment transaction towards the reserve value (as it implies no commitment transaction
2032         // will be generated which violates the remote reserve value).
2033         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2034         // To test this we:
2035         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2036         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2037         //    you only consider the value of the first HTLC, it may not),
2038         //  * start routing a third HTLC from A to B,
2039         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2040         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2041         //  * deliver the first fulfill from B
2042         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2043         //    claim,
2044         //  * deliver A's response CS and RAA.
2045         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2046         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2047         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2048         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2049         let chanmon_cfgs = create_chanmon_cfgs(2);
2050         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2051         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2052         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2053         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2054
2055         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2056         // Route the first two HTLCs.
2057         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2058         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2059         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2060
2061         // Start routing the third HTLC (this is just used to get everyone in the right state).
2062         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2063         let send_1 = {
2064                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2065                 check_added_monitors!(nodes[0], 1);
2066                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2067                 assert_eq!(events.len(), 1);
2068                 SendEvent::from_event(events.remove(0))
2069         };
2070
2071         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2072         // initial fulfill/CS.
2073         nodes[1].node.claim_funds(payment_preimage_1);
2074         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2075         check_added_monitors!(nodes[1], 1);
2076         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2077
2078         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2079         // remove the second HTLC when we send the HTLC back from B to A.
2080         nodes[1].node.claim_funds(payment_preimage_2);
2081         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2082         check_added_monitors!(nodes[1], 1);
2083         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2084
2085         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2086         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2087         check_added_monitors!(nodes[0], 1);
2088         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2089         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2090
2091         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2092         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2093         check_added_monitors!(nodes[1], 1);
2094         // B is already AwaitingRAA, so cant generate a CS here
2095         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2096
2097         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2098         check_added_monitors!(nodes[1], 1);
2099         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2100
2101         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2102         check_added_monitors!(nodes[0], 1);
2103         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2104
2105         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2106         check_added_monitors!(nodes[1], 1);
2107         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2108
2109         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2110         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2111         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2112         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2113         // on-chain as necessary).
2114         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2115         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2116         check_added_monitors!(nodes[0], 1);
2117         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2118         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2119
2120         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2121         check_added_monitors!(nodes[1], 1);
2122         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2123
2124         expect_pending_htlcs_forwardable!(nodes[1]);
2125         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2126
2127         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2128         // resolve the second HTLC from A's point of view.
2129         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2130         check_added_monitors!(nodes[0], 1);
2131         expect_payment_path_successful!(nodes[0]);
2132         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2133
2134         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2135         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2136         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2137         let send_2 = {
2138                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2139                 check_added_monitors!(nodes[1], 1);
2140                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2141                 assert_eq!(events.len(), 1);
2142                 SendEvent::from_event(events.remove(0))
2143         };
2144
2145         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2146         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2147         check_added_monitors!(nodes[0], 1);
2148         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2149
2150         // Now just resolve all the outstanding messages/HTLCs for completeness...
2151
2152         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2153         check_added_monitors!(nodes[1], 1);
2154         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2155
2156         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2157         check_added_monitors!(nodes[1], 1);
2158
2159         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2160         check_added_monitors!(nodes[0], 1);
2161         expect_payment_path_successful!(nodes[0]);
2162         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2163
2164         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2165         check_added_monitors!(nodes[1], 1);
2166         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
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
2171         expect_pending_htlcs_forwardable!(nodes[0]);
2172         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2173
2174         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2175         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2176 }
2177
2178 #[test]
2179 fn channel_monitor_network_test() {
2180         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2181         // tests that ChannelMonitor is able to recover from various states.
2182         let chanmon_cfgs = create_chanmon_cfgs(5);
2183         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2184         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2185         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2186
2187         // Create some initial channels
2188         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2189         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2190         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2191         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2192
2193         // Make sure all nodes are at the same starting height
2194         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2195         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2196         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2197         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2198         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2199
2200         // Rebalance the network a bit by relaying one payment through all the channels...
2201         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2202         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2203         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2204         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2205
2206         // Simple case with no pending HTLCs:
2207         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2208         check_added_monitors!(nodes[1], 1);
2209         check_closed_broadcast!(nodes[1], true);
2210         {
2211                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2212                 assert_eq!(node_txn.len(), 1);
2213                 mine_transaction(&nodes[0], &node_txn[0]);
2214                 check_added_monitors!(nodes[0], 1);
2215                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2216         }
2217         check_closed_broadcast!(nodes[0], true);
2218         assert_eq!(nodes[0].node.list_channels().len(), 0);
2219         assert_eq!(nodes[1].node.list_channels().len(), 1);
2220         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2221         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2222
2223         // One pending HTLC is discarded by the force-close:
2224         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2225
2226         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2227         // broadcasted until we reach the timelock time).
2228         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2229         check_closed_broadcast!(nodes[1], true);
2230         check_added_monitors!(nodes[1], 1);
2231         {
2232                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2233                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2234                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2235                 mine_transaction(&nodes[2], &node_txn[0]);
2236                 check_added_monitors!(nodes[2], 1);
2237                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2238         }
2239         check_closed_broadcast!(nodes[2], true);
2240         assert_eq!(nodes[1].node.list_channels().len(), 0);
2241         assert_eq!(nodes[2].node.list_channels().len(), 1);
2242         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2243         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2244
2245         macro_rules! claim_funds {
2246                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2247                         {
2248                                 $node.node.claim_funds($preimage);
2249                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2250                                 check_added_monitors!($node, 1);
2251
2252                                 let events = $node.node.get_and_clear_pending_msg_events();
2253                                 assert_eq!(events.len(), 1);
2254                                 match events[0] {
2255                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2256                                                 assert!(update_add_htlcs.is_empty());
2257                                                 assert!(update_fail_htlcs.is_empty());
2258                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2259                                         },
2260                                         _ => panic!("Unexpected event"),
2261                                 };
2262                         }
2263                 }
2264         }
2265
2266         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2267         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2268         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2269         check_added_monitors!(nodes[2], 1);
2270         check_closed_broadcast!(nodes[2], true);
2271         let node2_commitment_txid;
2272         {
2273                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2274                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2275                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2276                 node2_commitment_txid = node_txn[0].txid();
2277
2278                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2279                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2280                 mine_transaction(&nodes[3], &node_txn[0]);
2281                 check_added_monitors!(nodes[3], 1);
2282                 check_preimage_claim(&nodes[3], &node_txn);
2283         }
2284         check_closed_broadcast!(nodes[3], true);
2285         assert_eq!(nodes[2].node.list_channels().len(), 0);
2286         assert_eq!(nodes[3].node.list_channels().len(), 1);
2287         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2288         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2289
2290         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2291         // confusing us in the following tests.
2292         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2293
2294         // One pending HTLC to time out:
2295         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2296         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2297         // buffer space).
2298
2299         let (close_chan_update_1, close_chan_update_2) = {
2300                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2301                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2302                 assert_eq!(events.len(), 2);
2303                 let close_chan_update_1 = match events[0] {
2304                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2305                                 msg.clone()
2306                         },
2307                         _ => panic!("Unexpected event"),
2308                 };
2309                 match events[1] {
2310                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2311                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2312                         },
2313                         _ => panic!("Unexpected event"),
2314                 }
2315                 check_added_monitors!(nodes[3], 1);
2316
2317                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2318                 {
2319                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2320                         node_txn.retain(|tx| {
2321                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2322                                         false
2323                                 } else { true }
2324                         });
2325                 }
2326
2327                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2328
2329                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2330                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2331
2332                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2333                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2334                 assert_eq!(events.len(), 2);
2335                 let close_chan_update_2 = match events[0] {
2336                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2337                                 msg.clone()
2338                         },
2339                         _ => panic!("Unexpected event"),
2340                 };
2341                 match events[1] {
2342                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2343                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2344                         },
2345                         _ => panic!("Unexpected event"),
2346                 }
2347                 check_added_monitors!(nodes[4], 1);
2348                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2349
2350                 mine_transaction(&nodes[4], &node_txn[0]);
2351                 check_preimage_claim(&nodes[4], &node_txn);
2352                 (close_chan_update_1, close_chan_update_2)
2353         };
2354         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2355         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2356         assert_eq!(nodes[3].node.list_channels().len(), 0);
2357         assert_eq!(nodes[4].node.list_channels().len(), 0);
2358
2359         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2360         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2361         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2362 }
2363
2364 #[test]
2365 fn test_justice_tx() {
2366         // Test justice txn built on revoked HTLC-Success tx, against both sides
2367         let mut alice_config = UserConfig::default();
2368         alice_config.channel_handshake_config.announced_channel = true;
2369         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2370         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2371         let mut bob_config = UserConfig::default();
2372         bob_config.channel_handshake_config.announced_channel = true;
2373         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2374         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2375         let user_cfgs = [Some(alice_config), Some(bob_config)];
2376         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2377         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2378         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2379         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2380         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2381         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2382         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2383         // Create some new channels:
2384         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2385
2386         // A pending HTLC which will be revoked:
2387         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2388         // Get the will-be-revoked local txn from nodes[0]
2389         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2390         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2391         assert_eq!(revoked_local_txn[0].input.len(), 1);
2392         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2393         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2394         assert_eq!(revoked_local_txn[1].input.len(), 1);
2395         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2396         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2397         // Revoke the old state
2398         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2399
2400         {
2401                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2402                 {
2403                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2404                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2405                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2406
2407                         check_spends!(node_txn[0], revoked_local_txn[0]);
2408                         node_txn.swap_remove(0);
2409                         node_txn.truncate(1);
2410                 }
2411                 check_added_monitors!(nodes[1], 1);
2412                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2413                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2414
2415                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2416                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2417                 // Verify broadcast of revoked HTLC-timeout
2418                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2419                 check_added_monitors!(nodes[0], 1);
2420                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2421                 // Broadcast revoked HTLC-timeout on node 1
2422                 mine_transaction(&nodes[1], &node_txn[1]);
2423                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2424         }
2425         get_announce_close_broadcast_events(&nodes, 0, 1);
2426
2427         assert_eq!(nodes[0].node.list_channels().len(), 0);
2428         assert_eq!(nodes[1].node.list_channels().len(), 0);
2429
2430         // We test justice_tx build by A on B's revoked HTLC-Success tx
2431         // Create some new channels:
2432         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2433         {
2434                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2435                 node_txn.clear();
2436         }
2437
2438         // A pending HTLC which will be revoked:
2439         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2440         // Get the will-be-revoked local txn from B
2441         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2442         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2443         assert_eq!(revoked_local_txn[0].input.len(), 1);
2444         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2445         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2446         // Revoke the old state
2447         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2448         {
2449                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2450                 {
2451                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2452                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2453                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2454
2455                         check_spends!(node_txn[0], revoked_local_txn[0]);
2456                         node_txn.swap_remove(0);
2457                 }
2458                 check_added_monitors!(nodes[0], 1);
2459                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2460
2461                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2462                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2463                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2464                 check_added_monitors!(nodes[1], 1);
2465                 mine_transaction(&nodes[0], &node_txn[1]);
2466                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2467                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2468         }
2469         get_announce_close_broadcast_events(&nodes, 0, 1);
2470         assert_eq!(nodes[0].node.list_channels().len(), 0);
2471         assert_eq!(nodes[1].node.list_channels().len(), 0);
2472 }
2473
2474 #[test]
2475 fn revoked_output_claim() {
2476         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2477         // transaction is broadcast by its counterparty
2478         let chanmon_cfgs = create_chanmon_cfgs(2);
2479         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2480         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2481         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2482         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2483         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2484         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2485         assert_eq!(revoked_local_txn.len(), 1);
2486         // Only output is the full channel value back to nodes[0]:
2487         assert_eq!(revoked_local_txn[0].output.len(), 1);
2488         // Send a payment through, updating everyone's latest commitment txn
2489         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2490
2491         // Inform nodes[1] that nodes[0] broadcast a stale tx
2492         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2493         check_added_monitors!(nodes[1], 1);
2494         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2495         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2496         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2497
2498         check_spends!(node_txn[0], revoked_local_txn[0]);
2499         check_spends!(node_txn[1], chan_1.3);
2500
2501         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2502         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2503         get_announce_close_broadcast_events(&nodes, 0, 1);
2504         check_added_monitors!(nodes[0], 1);
2505         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2506 }
2507
2508 #[test]
2509 fn claim_htlc_outputs_shared_tx() {
2510         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2511         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2512         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2513         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2514         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2515         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2516
2517         // Create some new channel:
2518         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2519
2520         // Rebalance the network to generate htlc in the two directions
2521         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2522         // 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
2523         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2524         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2525
2526         // Get the will-be-revoked local txn from node[0]
2527         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2528         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2529         assert_eq!(revoked_local_txn[0].input.len(), 1);
2530         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2531         assert_eq!(revoked_local_txn[1].input.len(), 1);
2532         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2533         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2534         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2535
2536         //Revoke the old state
2537         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2538
2539         {
2540                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2541                 check_added_monitors!(nodes[0], 1);
2542                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2543                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2544                 check_added_monitors!(nodes[1], 1);
2545                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2546                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2547                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2548
2549                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2550                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2551
2552                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2553                 check_spends!(node_txn[0], revoked_local_txn[0]);
2554
2555                 let mut witness_lens = BTreeSet::new();
2556                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2557                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2558                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2559                 assert_eq!(witness_lens.len(), 3);
2560                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2561                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2562                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2563
2564                 // Next nodes[1] broadcasts its current local tx state:
2565                 assert_eq!(node_txn[1].input.len(), 1);
2566                 check_spends!(node_txn[1], chan_1.3);
2567
2568                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2569                 // ANTI_REORG_DELAY confirmations.
2570                 mine_transaction(&nodes[1], &node_txn[0]);
2571                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2572                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2573         }
2574         get_announce_close_broadcast_events(&nodes, 0, 1);
2575         assert_eq!(nodes[0].node.list_channels().len(), 0);
2576         assert_eq!(nodes[1].node.list_channels().len(), 0);
2577 }
2578
2579 #[test]
2580 fn claim_htlc_outputs_single_tx() {
2581         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2582         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2583         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2584         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2585         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2586         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2587
2588         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2589
2590         // Rebalance the network to generate htlc in the two directions
2591         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2592         // 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
2593         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2594         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2595         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2596
2597         // Get the will-be-revoked local txn from node[0]
2598         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2599
2600         //Revoke the old state
2601         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2602
2603         {
2604                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2605                 check_added_monitors!(nodes[0], 1);
2606                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2607                 check_added_monitors!(nodes[1], 1);
2608                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2609                 let mut events = nodes[0].node.get_and_clear_pending_events();
2610                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2611                 match events[1] {
2612                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2613                         _ => panic!("Unexpected event"),
2614                 }
2615
2616                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2617                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2618
2619                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2620                 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2621
2622                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2623                 assert_eq!(node_txn[0].input.len(), 1);
2624                 check_spends!(node_txn[0], chan_1.3);
2625                 assert_eq!(node_txn[1].input.len(), 1);
2626                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2627                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2628                 check_spends!(node_txn[1], node_txn[0]);
2629
2630                 // Justice transactions are indices 1-2-4
2631                 assert_eq!(node_txn[2].input.len(), 1);
2632                 assert_eq!(node_txn[3].input.len(), 1);
2633                 assert_eq!(node_txn[4].input.len(), 1);
2634
2635                 check_spends!(node_txn[2], revoked_local_txn[0]);
2636                 check_spends!(node_txn[3], revoked_local_txn[0]);
2637                 check_spends!(node_txn[4], revoked_local_txn[0]);
2638
2639                 let mut witness_lens = BTreeSet::new();
2640                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2641                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2642                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2643                 assert_eq!(witness_lens.len(), 3);
2644                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2645                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2646                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2647
2648                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2649                 // ANTI_REORG_DELAY confirmations.
2650                 mine_transaction(&nodes[1], &node_txn[2]);
2651                 mine_transaction(&nodes[1], &node_txn[3]);
2652                 mine_transaction(&nodes[1], &node_txn[4]);
2653                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2654                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2655         }
2656         get_announce_close_broadcast_events(&nodes, 0, 1);
2657         assert_eq!(nodes[0].node.list_channels().len(), 0);
2658         assert_eq!(nodes[1].node.list_channels().len(), 0);
2659 }
2660
2661 #[test]
2662 fn test_htlc_on_chain_success() {
2663         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2664         // the preimage backward accordingly. So here we test that ChannelManager is
2665         // broadcasting the right event to other nodes in payment path.
2666         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2667         // A --------------------> B ----------------------> C (preimage)
2668         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2669         // commitment transaction was broadcast.
2670         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2671         // towards B.
2672         // B should be able to claim via preimage if A then broadcasts its local tx.
2673         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2674         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2675         // PaymentSent event).
2676
2677         let chanmon_cfgs = create_chanmon_cfgs(3);
2678         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2679         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2680         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2681
2682         // Create some initial channels
2683         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2684         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2685
2686         // Ensure all nodes are at the same height
2687         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2688         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2689         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2690         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2691
2692         // Rebalance the network a bit by relaying one payment through all the channels...
2693         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2694         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2695
2696         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2697         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2698
2699         // Broadcast legit commitment tx from C on B's chain
2700         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2701         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2702         assert_eq!(commitment_tx.len(), 1);
2703         check_spends!(commitment_tx[0], chan_2.3);
2704         nodes[2].node.claim_funds(our_payment_preimage);
2705         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2706         nodes[2].node.claim_funds(our_payment_preimage_2);
2707         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2708         check_added_monitors!(nodes[2], 2);
2709         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2710         assert!(updates.update_add_htlcs.is_empty());
2711         assert!(updates.update_fail_htlcs.is_empty());
2712         assert!(updates.update_fail_malformed_htlcs.is_empty());
2713         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2714
2715         mine_transaction(&nodes[2], &commitment_tx[0]);
2716         check_closed_broadcast!(nodes[2], true);
2717         check_added_monitors!(nodes[2], 1);
2718         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2719         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)
2720         assert_eq!(node_txn.len(), 5);
2721         assert_eq!(node_txn[0], node_txn[3]);
2722         assert_eq!(node_txn[1], node_txn[4]);
2723         assert_eq!(node_txn[2], commitment_tx[0]);
2724         check_spends!(node_txn[0], commitment_tx[0]);
2725         check_spends!(node_txn[1], commitment_tx[0]);
2726         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2727         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2728         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2729         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2730         assert_eq!(node_txn[0].lock_time, 0);
2731         assert_eq!(node_txn[1].lock_time, 0);
2732
2733         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2734         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2735         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2736         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2737         {
2738                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2739                 assert_eq!(added_monitors.len(), 1);
2740                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2741                 added_monitors.clear();
2742         }
2743         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2744         assert_eq!(forwarded_events.len(), 3);
2745         match forwarded_events[0] {
2746                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2747                 _ => panic!("Unexpected event"),
2748         }
2749         let chan_id = Some(chan_1.2);
2750         match forwarded_events[1] {
2751                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2752                         assert_eq!(fee_earned_msat, Some(1000));
2753                         assert_eq!(prev_channel_id, chan_id);
2754                         assert_eq!(claim_from_onchain_tx, true);
2755                         assert_eq!(next_channel_id, Some(chan_2.2));
2756                 },
2757                 _ => panic!()
2758         }
2759         match forwarded_events[2] {
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         let events = nodes[1].node.get_and_clear_pending_msg_events();
2769         {
2770                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2771                 assert_eq!(added_monitors.len(), 2);
2772                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2773                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2774                 added_monitors.clear();
2775         }
2776         assert_eq!(events.len(), 3);
2777         match events[0] {
2778                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2779                 _ => panic!("Unexpected event"),
2780         }
2781         match events[1] {
2782                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2783                 _ => panic!("Unexpected event"),
2784         }
2785
2786         match events[2] {
2787                 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, .. } } => {
2788                         assert!(update_add_htlcs.is_empty());
2789                         assert!(update_fail_htlcs.is_empty());
2790                         assert_eq!(update_fulfill_htlcs.len(), 1);
2791                         assert!(update_fail_malformed_htlcs.is_empty());
2792                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2793                 },
2794                 _ => panic!("Unexpected event"),
2795         };
2796         macro_rules! check_tx_local_broadcast {
2797                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2798                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2799                         assert_eq!(node_txn.len(), 3);
2800                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2801                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2802                         check_spends!(node_txn[1], $commitment_tx);
2803                         check_spends!(node_txn[2], $commitment_tx);
2804                         assert_ne!(node_txn[1].lock_time, 0);
2805                         assert_ne!(node_txn[2].lock_time, 0);
2806                         if $htlc_offered {
2807                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2808                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2809                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2810                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2811                         } else {
2812                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2813                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2814                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2815                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2816                         }
2817                         check_spends!(node_txn[0], $chan_tx);
2818                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2819                         node_txn.clear();
2820                 } }
2821         }
2822         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2823         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2824         // timeout-claim of the output that nodes[2] just claimed via success.
2825         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2826
2827         // Broadcast legit commitment tx from A on B's chain
2828         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2829         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2830         check_spends!(node_a_commitment_tx[0], chan_1.3);
2831         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2832         check_closed_broadcast!(nodes[1], true);
2833         check_added_monitors!(nodes[1], 1);
2834         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2835         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2836         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2837         let commitment_spend =
2838                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2839                         check_spends!(node_txn[1], commitment_tx[0]);
2840                         check_spends!(node_txn[2], commitment_tx[0]);
2841                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2842                         &node_txn[0]
2843                 } else {
2844                         check_spends!(node_txn[0], commitment_tx[0]);
2845                         check_spends!(node_txn[1], commitment_tx[0]);
2846                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2847                         &node_txn[2]
2848                 };
2849
2850         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2851         assert_eq!(commitment_spend.input.len(), 2);
2852         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2853         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2854         assert_eq!(commitment_spend.lock_time, 0);
2855         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2856         check_spends!(node_txn[3], chan_1.3);
2857         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2858         check_spends!(node_txn[4], node_txn[3]);
2859         check_spends!(node_txn[5], node_txn[3]);
2860         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2861         // we already checked the same situation with A.
2862
2863         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2864         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2865         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2866         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2867         check_closed_broadcast!(nodes[0], true);
2868         check_added_monitors!(nodes[0], 1);
2869         let events = nodes[0].node.get_and_clear_pending_events();
2870         assert_eq!(events.len(), 5);
2871         let mut first_claimed = false;
2872         for event in events {
2873                 match event {
2874                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2875                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2876                                         assert!(!first_claimed);
2877                                         first_claimed = true;
2878                                 } else {
2879                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2880                                         assert_eq!(payment_hash, payment_hash_2);
2881                                 }
2882                         },
2883                         Event::PaymentPathSuccessful { .. } => {},
2884                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2885                         _ => panic!("Unexpected event"),
2886                 }
2887         }
2888         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2889 }
2890
2891 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2892         // Test that in case of a unilateral close onchain, we detect the state of output and
2893         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2894         // broadcasting the right event to other nodes in payment path.
2895         // A ------------------> B ----------------------> C (timeout)
2896         //    B's commitment tx                 C's commitment tx
2897         //            \                                  \
2898         //         B's HTLC timeout tx               B's timeout tx
2899
2900         let chanmon_cfgs = create_chanmon_cfgs(3);
2901         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2902         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2903         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2904         *nodes[0].connect_style.borrow_mut() = connect_style;
2905         *nodes[1].connect_style.borrow_mut() = connect_style;
2906         *nodes[2].connect_style.borrow_mut() = connect_style;
2907
2908         // Create some intial channels
2909         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2910         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2911
2912         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2913         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2914         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2915
2916         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2917
2918         // Broadcast legit commitment tx from C on B's chain
2919         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2920         check_spends!(commitment_tx[0], chan_2.3);
2921         nodes[2].node.fail_htlc_backwards(&payment_hash);
2922         check_added_monitors!(nodes[2], 0);
2923         expect_pending_htlcs_forwardable!(nodes[2]);
2924         check_added_monitors!(nodes[2], 1);
2925
2926         let events = nodes[2].node.get_and_clear_pending_msg_events();
2927         assert_eq!(events.len(), 1);
2928         match events[0] {
2929                 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, .. } } => {
2930                         assert!(update_add_htlcs.is_empty());
2931                         assert!(!update_fail_htlcs.is_empty());
2932                         assert!(update_fulfill_htlcs.is_empty());
2933                         assert!(update_fail_malformed_htlcs.is_empty());
2934                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2935                 },
2936                 _ => panic!("Unexpected event"),
2937         };
2938         mine_transaction(&nodes[2], &commitment_tx[0]);
2939         check_closed_broadcast!(nodes[2], true);
2940         check_added_monitors!(nodes[2], 1);
2941         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2942         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2943         assert_eq!(node_txn.len(), 1);
2944         check_spends!(node_txn[0], chan_2.3);
2945         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2946
2947         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2948         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2949         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2950         mine_transaction(&nodes[1], &commitment_tx[0]);
2951         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2952         let timeout_tx;
2953         {
2954                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2955                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2956                 assert_eq!(node_txn[0], node_txn[3]);
2957                 assert_eq!(node_txn[1], node_txn[4]);
2958
2959                 check_spends!(node_txn[2], commitment_tx[0]);
2960                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2961
2962                 check_spends!(node_txn[0], chan_2.3);
2963                 check_spends!(node_txn[1], node_txn[0]);
2964                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2965                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2966
2967                 timeout_tx = node_txn[2].clone();
2968                 node_txn.clear();
2969         }
2970
2971         mine_transaction(&nodes[1], &timeout_tx);
2972         check_added_monitors!(nodes[1], 1);
2973         check_closed_broadcast!(nodes[1], true);
2974         {
2975                 // B will rebroadcast a fee-bumped timeout transaction here.
2976                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2977                 assert_eq!(node_txn.len(), 1);
2978                 check_spends!(node_txn[0], commitment_tx[0]);
2979         }
2980
2981         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2982         {
2983                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2984                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2985                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2986                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2987                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2988                 if node_txn.len() == 1 {
2989                         check_spends!(node_txn[0], chan_2.3);
2990                 } else {
2991                         assert_eq!(node_txn.len(), 0);
2992                 }
2993         }
2994
2995         expect_pending_htlcs_forwardable!(nodes[1]);
2996         check_added_monitors!(nodes[1], 1);
2997         let events = nodes[1].node.get_and_clear_pending_msg_events();
2998         assert_eq!(events.len(), 1);
2999         match events[0] {
3000                 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, .. } } => {
3001                         assert!(update_add_htlcs.is_empty());
3002                         assert!(!update_fail_htlcs.is_empty());
3003                         assert!(update_fulfill_htlcs.is_empty());
3004                         assert!(update_fail_malformed_htlcs.is_empty());
3005                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3006                 },
3007                 _ => panic!("Unexpected event"),
3008         };
3009
3010         // Broadcast legit commitment tx from B on A's chain
3011         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3012         check_spends!(commitment_tx[0], chan_1.3);
3013
3014         mine_transaction(&nodes[0], &commitment_tx[0]);
3015         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3016
3017         check_closed_broadcast!(nodes[0], true);
3018         check_added_monitors!(nodes[0], 1);
3019         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3020         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3021         assert_eq!(node_txn.len(), 2);
3022         check_spends!(node_txn[0], chan_1.3);
3023         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3024         check_spends!(node_txn[1], commitment_tx[0]);
3025         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3026 }
3027
3028 #[test]
3029 fn test_htlc_on_chain_timeout() {
3030         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3031         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3032         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3033 }
3034
3035 #[test]
3036 fn test_simple_commitment_revoked_fail_backward() {
3037         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3038         // and fail backward accordingly.
3039
3040         let chanmon_cfgs = create_chanmon_cfgs(3);
3041         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3042         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3043         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3044
3045         // Create some initial channels
3046         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3047         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3048
3049         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3050         // Get the will-be-revoked local txn from nodes[2]
3051         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3052         // Revoke the old state
3053         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3054
3055         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3056
3057         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3058         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3059         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3060         check_added_monitors!(nodes[1], 1);
3061         check_closed_broadcast!(nodes[1], true);
3062
3063         expect_pending_htlcs_forwardable!(nodes[1]);
3064         check_added_monitors!(nodes[1], 1);
3065         let events = nodes[1].node.get_and_clear_pending_msg_events();
3066         assert_eq!(events.len(), 1);
3067         match events[0] {
3068                 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, .. } } => {
3069                         assert!(update_add_htlcs.is_empty());
3070                         assert_eq!(update_fail_htlcs.len(), 1);
3071                         assert!(update_fulfill_htlcs.is_empty());
3072                         assert!(update_fail_malformed_htlcs.is_empty());
3073                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3074
3075                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3076                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3077                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3078                 },
3079                 _ => panic!("Unexpected event"),
3080         }
3081 }
3082
3083 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3084         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3085         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3086         // commitment transaction anymore.
3087         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3088         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3089         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3090         // technically disallowed and we should probably handle it reasonably.
3091         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3092         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3093         // transactions:
3094         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3095         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3096         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3097         //   and once they revoke the previous commitment transaction (allowing us to send a new
3098         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3099         let chanmon_cfgs = create_chanmon_cfgs(3);
3100         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3101         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3102         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3103
3104         // Create some initial channels
3105         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3106         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3107
3108         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 });
3109         // Get the will-be-revoked local txn from nodes[2]
3110         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3111         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3112         // Revoke the old state
3113         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3114
3115         let value = if use_dust {
3116                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3117                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3118                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3119         } else { 3000000 };
3120
3121         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3122         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3123         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3124
3125         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3126         expect_pending_htlcs_forwardable!(nodes[2]);
3127         check_added_monitors!(nodes[2], 1);
3128         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3129         assert!(updates.update_add_htlcs.is_empty());
3130         assert!(updates.update_fulfill_htlcs.is_empty());
3131         assert!(updates.update_fail_malformed_htlcs.is_empty());
3132         assert_eq!(updates.update_fail_htlcs.len(), 1);
3133         assert!(updates.update_fee.is_none());
3134         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3135         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3136         // Drop the last RAA from 3 -> 2
3137
3138         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3139         expect_pending_htlcs_forwardable!(nodes[2]);
3140         check_added_monitors!(nodes[2], 1);
3141         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3142         assert!(updates.update_add_htlcs.is_empty());
3143         assert!(updates.update_fulfill_htlcs.is_empty());
3144         assert!(updates.update_fail_malformed_htlcs.is_empty());
3145         assert_eq!(updates.update_fail_htlcs.len(), 1);
3146         assert!(updates.update_fee.is_none());
3147         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3148         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3149         check_added_monitors!(nodes[1], 1);
3150         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3151         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3152         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3153         check_added_monitors!(nodes[2], 1);
3154
3155         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3156         expect_pending_htlcs_forwardable!(nodes[2]);
3157         check_added_monitors!(nodes[2], 1);
3158         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3159         assert!(updates.update_add_htlcs.is_empty());
3160         assert!(updates.update_fulfill_htlcs.is_empty());
3161         assert!(updates.update_fail_malformed_htlcs.is_empty());
3162         assert_eq!(updates.update_fail_htlcs.len(), 1);
3163         assert!(updates.update_fee.is_none());
3164         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3165         // At this point first_payment_hash has dropped out of the latest two commitment
3166         // transactions that nodes[1] is tracking...
3167         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3168         check_added_monitors!(nodes[1], 1);
3169         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3170         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3171         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3172         check_added_monitors!(nodes[2], 1);
3173
3174         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3175         // on nodes[2]'s RAA.
3176         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3177         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3178         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3179         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3180         check_added_monitors!(nodes[1], 0);
3181
3182         if deliver_bs_raa {
3183                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3184                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3185                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3186                 check_added_monitors!(nodes[1], 1);
3187                 let events = nodes[1].node.get_and_clear_pending_events();
3188                 assert_eq!(events.len(), 1);
3189                 match events[0] {
3190                         Event::PendingHTLCsForwardable { .. } => { },
3191                         _ => panic!("Unexpected event"),
3192                 };
3193                 // Deliberately don't process the pending fail-back so they all fail back at once after
3194                 // block connection just like the !deliver_bs_raa case
3195         }
3196
3197         let mut failed_htlcs = HashSet::new();
3198         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3199
3200         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3201         check_added_monitors!(nodes[1], 1);
3202         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3203         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3204
3205         let events = nodes[1].node.get_and_clear_pending_events();
3206         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3207         match events[0] {
3208                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3209                 _ => panic!("Unexepected event"),
3210         }
3211         match events[1] {
3212                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3213                         assert_eq!(*payment_hash, fourth_payment_hash);
3214                 },
3215                 _ => panic!("Unexpected event"),
3216         }
3217         if !deliver_bs_raa {
3218                 match events[2] {
3219                         Event::PaymentFailed { ref payment_hash, .. } => {
3220                                 assert_eq!(*payment_hash, fourth_payment_hash);
3221                         },
3222                         _ => panic!("Unexpected event"),
3223                 }
3224                 match events[3] {
3225                         Event::PendingHTLCsForwardable { .. } => { },
3226                         _ => panic!("Unexpected event"),
3227                 };
3228         }
3229         nodes[1].node.process_pending_htlc_forwards();
3230         check_added_monitors!(nodes[1], 1);
3231
3232         let events = nodes[1].node.get_and_clear_pending_msg_events();
3233         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3234         match events[if deliver_bs_raa { 1 } else { 0 }] {
3235                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3236                 _ => panic!("Unexpected event"),
3237         }
3238         match events[if deliver_bs_raa { 2 } else { 1 }] {
3239                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3240                         assert_eq!(channel_id, chan_2.2);
3241                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3242                 },
3243                 _ => panic!("Unexpected event"),
3244         }
3245         if deliver_bs_raa {
3246                 match events[0] {
3247                         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, .. } } => {
3248                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3249                                 assert_eq!(update_add_htlcs.len(), 1);
3250                                 assert!(update_fulfill_htlcs.is_empty());
3251                                 assert!(update_fail_htlcs.is_empty());
3252                                 assert!(update_fail_malformed_htlcs.is_empty());
3253                         },
3254                         _ => panic!("Unexpected event"),
3255                 }
3256         }
3257         match events[if deliver_bs_raa { 3 } else { 2 }] {
3258                 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, .. } } => {
3259                         assert!(update_add_htlcs.is_empty());
3260                         assert_eq!(update_fail_htlcs.len(), 3);
3261                         assert!(update_fulfill_htlcs.is_empty());
3262                         assert!(update_fail_malformed_htlcs.is_empty());
3263                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3264
3265                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3266                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3267                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3268
3269                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3270
3271                         let events = nodes[0].node.get_and_clear_pending_events();
3272                         assert_eq!(events.len(), 3);
3273                         match events[0] {
3274                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3275                                         assert!(failed_htlcs.insert(payment_hash.0));
3276                                         // If we delivered B's RAA we got an unknown preimage error, not something
3277                                         // that we should update our routing table for.
3278                                         if !deliver_bs_raa {
3279                                                 assert!(network_update.is_some());
3280                                         }
3281                                 },
3282                                 _ => panic!("Unexpected event"),
3283                         }
3284                         match events[1] {
3285                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3286                                         assert!(failed_htlcs.insert(payment_hash.0));
3287                                         assert!(network_update.is_some());
3288                                 },
3289                                 _ => panic!("Unexpected event"),
3290                         }
3291                         match events[2] {
3292                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3293                                         assert!(failed_htlcs.insert(payment_hash.0));
3294                                         assert!(network_update.is_some());
3295                                 },
3296                                 _ => panic!("Unexpected event"),
3297                         }
3298                 },
3299                 _ => panic!("Unexpected event"),
3300         }
3301
3302         assert!(failed_htlcs.contains(&first_payment_hash.0));
3303         assert!(failed_htlcs.contains(&second_payment_hash.0));
3304         assert!(failed_htlcs.contains(&third_payment_hash.0));
3305 }
3306
3307 #[test]
3308 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3309         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3310         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3311         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3312         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3313 }
3314
3315 #[test]
3316 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3317         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3318         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3319         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3320         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3321 }
3322
3323 #[test]
3324 fn fail_backward_pending_htlc_upon_channel_failure() {
3325         let chanmon_cfgs = create_chanmon_cfgs(2);
3326         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3327         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3328         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3329         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3330
3331         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3332         {
3333                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3334                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3335                 check_added_monitors!(nodes[0], 1);
3336
3337                 let payment_event = {
3338                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3339                         assert_eq!(events.len(), 1);
3340                         SendEvent::from_event(events.remove(0))
3341                 };
3342                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3343                 assert_eq!(payment_event.msgs.len(), 1);
3344         }
3345
3346         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3347         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3348         {
3349                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3350                 check_added_monitors!(nodes[0], 0);
3351
3352                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3353         }
3354
3355         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3356         {
3357                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3358
3359                 let secp_ctx = Secp256k1::new();
3360                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3361                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3362                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3363                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3364                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3365
3366                 // Send a 0-msat update_add_htlc to fail the channel.
3367                 let update_add_htlc = msgs::UpdateAddHTLC {
3368                         channel_id: chan.2,
3369                         htlc_id: 0,
3370                         amount_msat: 0,
3371                         payment_hash,
3372                         cltv_expiry,
3373                         onion_routing_packet,
3374                 };
3375                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3376         }
3377         let events = nodes[0].node.get_and_clear_pending_events();
3378         assert_eq!(events.len(), 2);
3379         // Check that Alice fails backward the pending HTLC from the second payment.
3380         match events[0] {
3381                 Event::PaymentPathFailed { payment_hash, .. } => {
3382                         assert_eq!(payment_hash, failed_payment_hash);
3383                 },
3384                 _ => panic!("Unexpected event"),
3385         }
3386         match events[1] {
3387                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3388                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3389                 },
3390                 _ => panic!("Unexpected event {:?}", events[1]),
3391         }
3392         check_closed_broadcast!(nodes[0], true);
3393         check_added_monitors!(nodes[0], 1);
3394 }
3395
3396 #[test]
3397 fn test_htlc_ignore_latest_remote_commitment() {
3398         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3399         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3400         let chanmon_cfgs = create_chanmon_cfgs(2);
3401         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3402         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3403         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3404         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3405
3406         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3407         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3408         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3409         check_closed_broadcast!(nodes[0], true);
3410         check_added_monitors!(nodes[0], 1);
3411         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3412
3413         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3414         assert_eq!(node_txn.len(), 3);
3415         assert_eq!(node_txn[0], node_txn[1]);
3416
3417         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3418         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3419         check_closed_broadcast!(nodes[1], true);
3420         check_added_monitors!(nodes[1], 1);
3421         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3422
3423         // Duplicate the connect_block call since this may happen due to other listeners
3424         // registering new transactions
3425         header.prev_blockhash = header.block_hash();
3426         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3427 }
3428
3429 #[test]
3430 fn test_force_close_fail_back() {
3431         // Check which HTLCs are failed-backwards on channel force-closure
3432         let chanmon_cfgs = create_chanmon_cfgs(3);
3433         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3434         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3435         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3436         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3437         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3438
3439         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3440
3441         let mut payment_event = {
3442                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3443                 check_added_monitors!(nodes[0], 1);
3444
3445                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3446                 assert_eq!(events.len(), 1);
3447                 SendEvent::from_event(events.remove(0))
3448         };
3449
3450         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3451         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3452
3453         expect_pending_htlcs_forwardable!(nodes[1]);
3454
3455         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3456         assert_eq!(events_2.len(), 1);
3457         payment_event = SendEvent::from_event(events_2.remove(0));
3458         assert_eq!(payment_event.msgs.len(), 1);
3459
3460         check_added_monitors!(nodes[1], 1);
3461         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3462         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3463         check_added_monitors!(nodes[2], 1);
3464         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3465
3466         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3467         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3468         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3469
3470         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3471         check_closed_broadcast!(nodes[2], true);
3472         check_added_monitors!(nodes[2], 1);
3473         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3474         let tx = {
3475                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3476                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3477                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3478                 // back to nodes[1] upon timeout otherwise.
3479                 assert_eq!(node_txn.len(), 1);
3480                 node_txn.remove(0)
3481         };
3482
3483         mine_transaction(&nodes[1], &tx);
3484
3485         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3486         check_closed_broadcast!(nodes[1], true);
3487         check_added_monitors!(nodes[1], 1);
3488         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3489
3490         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3491         {
3492                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3493                         .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);
3494         }
3495         mine_transaction(&nodes[2], &tx);
3496         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3497         assert_eq!(node_txn.len(), 1);
3498         assert_eq!(node_txn[0].input.len(), 1);
3499         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3500         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3501         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3502
3503         check_spends!(node_txn[0], tx);
3504 }
3505
3506 #[test]
3507 fn test_dup_events_on_peer_disconnect() {
3508         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3509         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3510         // as we used to generate the event immediately upon receipt of the payment preimage in the
3511         // update_fulfill_htlc message.
3512
3513         let chanmon_cfgs = create_chanmon_cfgs(2);
3514         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3515         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3516         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3517         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3518
3519         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3520
3521         nodes[1].node.claim_funds(payment_preimage);
3522         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3523         check_added_monitors!(nodes[1], 1);
3524         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3525         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3526         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3527
3528         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3529         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3530
3531         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3532         expect_payment_path_successful!(nodes[0]);
3533 }
3534
3535 #[test]
3536 fn test_peer_disconnected_before_funding_broadcasted() {
3537         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3538         // before the funding transaction has been broadcasted.
3539         let chanmon_cfgs = create_chanmon_cfgs(2);
3540         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3541         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3542         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3543
3544         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3545         // broadcasted, even though it's created by `nodes[0]`.
3546         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();
3547         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3548         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3549         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3550         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3551
3552         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3553         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3554
3555         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3556
3557         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3558         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3559
3560         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3561         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3562         // broadcasted.
3563         {
3564                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3565         }
3566
3567         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3568         // disconnected before the funding transaction was broadcasted.
3569         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3570         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3571
3572         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3573         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3574 }
3575
3576 #[test]
3577 fn test_simple_peer_disconnect() {
3578         // Test that we can reconnect when there are no lost messages
3579         let chanmon_cfgs = create_chanmon_cfgs(3);
3580         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3581         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3582         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3583         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3584         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3585
3586         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3587         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3588         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3589
3590         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3591         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3592         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3593         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3594
3595         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3596         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3597         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3598
3599         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3600         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3601         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3602         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3603
3604         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3605         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3606
3607         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3608         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3609
3610         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3611         {
3612                 let events = nodes[0].node.get_and_clear_pending_events();
3613                 assert_eq!(events.len(), 3);
3614                 match events[0] {
3615                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3616                                 assert_eq!(payment_preimage, payment_preimage_3);
3617                                 assert_eq!(payment_hash, payment_hash_3);
3618                         },
3619                         _ => panic!("Unexpected event"),
3620                 }
3621                 match events[1] {
3622                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3623                                 assert_eq!(payment_hash, payment_hash_5);
3624                                 assert!(rejected_by_dest);
3625                         },
3626                         _ => panic!("Unexpected event"),
3627                 }
3628                 match events[2] {
3629                         Event::PaymentPathSuccessful { .. } => {},
3630                         _ => panic!("Unexpected event"),
3631                 }
3632         }
3633
3634         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3635         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3636 }
3637
3638 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3639         // Test that we can reconnect when in-flight HTLC updates get dropped
3640         let chanmon_cfgs = create_chanmon_cfgs(2);
3641         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3642         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3643         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3644
3645         let mut as_channel_ready = None;
3646         if messages_delivered == 0 {
3647                 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3648                 as_channel_ready = Some(channel_ready);
3649                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3650                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3651                 // it before the channel_reestablish message.
3652         } else {
3653                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3654         }
3655
3656         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3657
3658         let payment_event = {
3659                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3660                 check_added_monitors!(nodes[0], 1);
3661
3662                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3663                 assert_eq!(events.len(), 1);
3664                 SendEvent::from_event(events.remove(0))
3665         };
3666         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3667
3668         if messages_delivered < 2 {
3669                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3670         } else {
3671                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3672                 if messages_delivered >= 3 {
3673                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3674                         check_added_monitors!(nodes[1], 1);
3675                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3676
3677                         if messages_delivered >= 4 {
3678                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3679                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3680                                 check_added_monitors!(nodes[0], 1);
3681
3682                                 if messages_delivered >= 5 {
3683                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3684                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3685                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3686                                         check_added_monitors!(nodes[0], 1);
3687
3688                                         if messages_delivered >= 6 {
3689                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3690                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3691                                                 check_added_monitors!(nodes[1], 1);
3692                                         }
3693                                 }
3694                         }
3695                 }
3696         }
3697
3698         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3699         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3700         if messages_delivered < 3 {
3701                 if simulate_broken_lnd {
3702                         // lnd has a long-standing bug where they send a channel_ready prior to a
3703                         // channel_reestablish if you reconnect prior to channel_ready time.
3704                         //
3705                         // Here we simulate that behavior, delivering a channel_ready immediately on
3706                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3707                         // in `reconnect_nodes` but we currently don't fail based on that.
3708                         //
3709                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3710                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3711                 }
3712                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3713                 // received on either side, both sides will need to resend them.
3714                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3715         } else if messages_delivered == 3 {
3716                 // nodes[0] still wants its RAA + commitment_signed
3717                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3718         } else if messages_delivered == 4 {
3719                 // nodes[0] still wants its commitment_signed
3720                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3721         } else if messages_delivered == 5 {
3722                 // nodes[1] still wants its final RAA
3723                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3724         } else if messages_delivered == 6 {
3725                 // Everything was delivered...
3726                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3727         }
3728
3729         let events_1 = nodes[1].node.get_and_clear_pending_events();
3730         assert_eq!(events_1.len(), 1);
3731         match events_1[0] {
3732                 Event::PendingHTLCsForwardable { .. } => { },
3733                 _ => panic!("Unexpected event"),
3734         };
3735
3736         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3737         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3738         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3739
3740         nodes[1].node.process_pending_htlc_forwards();
3741
3742         let events_2 = nodes[1].node.get_and_clear_pending_events();
3743         assert_eq!(events_2.len(), 1);
3744         match events_2[0] {
3745                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3746                         assert_eq!(payment_hash_1, *payment_hash);
3747                         assert_eq!(amount_msat, 1_000_000);
3748                         match &purpose {
3749                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3750                                         assert!(payment_preimage.is_none());
3751                                         assert_eq!(payment_secret_1, *payment_secret);
3752                                 },
3753                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3754                         }
3755                 },
3756                 _ => panic!("Unexpected event"),
3757         }
3758
3759         nodes[1].node.claim_funds(payment_preimage_1);
3760         check_added_monitors!(nodes[1], 1);
3761         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3762
3763         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3764         assert_eq!(events_3.len(), 1);
3765         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3766                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3767                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3768                         assert!(updates.update_add_htlcs.is_empty());
3769                         assert!(updates.update_fail_htlcs.is_empty());
3770                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3771                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3772                         assert!(updates.update_fee.is_none());
3773                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3774                 },
3775                 _ => panic!("Unexpected event"),
3776         };
3777
3778         if messages_delivered >= 1 {
3779                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3780
3781                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3782                 assert_eq!(events_4.len(), 1);
3783                 match events_4[0] {
3784                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3785                                 assert_eq!(payment_preimage_1, *payment_preimage);
3786                                 assert_eq!(payment_hash_1, *payment_hash);
3787                         },
3788                         _ => panic!("Unexpected event"),
3789                 }
3790
3791                 if messages_delivered >= 2 {
3792                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3793                         check_added_monitors!(nodes[0], 1);
3794                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3795
3796                         if messages_delivered >= 3 {
3797                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3798                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3799                                 check_added_monitors!(nodes[1], 1);
3800
3801                                 if messages_delivered >= 4 {
3802                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3803                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3804                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3805                                         check_added_monitors!(nodes[1], 1);
3806
3807                                         if messages_delivered >= 5 {
3808                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3809                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3810                                                 check_added_monitors!(nodes[0], 1);
3811                                         }
3812                                 }
3813                         }
3814                 }
3815         }
3816
3817         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3818         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3819         if messages_delivered < 2 {
3820                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3821                 if messages_delivered < 1 {
3822                         expect_payment_sent!(nodes[0], payment_preimage_1);
3823                 } else {
3824                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3825                 }
3826         } else if messages_delivered == 2 {
3827                 // nodes[0] still wants its RAA + commitment_signed
3828                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3829         } else if messages_delivered == 3 {
3830                 // nodes[0] still wants its commitment_signed
3831                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3832         } else if messages_delivered == 4 {
3833                 // nodes[1] still wants its final RAA
3834                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3835         } else if messages_delivered == 5 {
3836                 // Everything was delivered...
3837                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3838         }
3839
3840         if messages_delivered == 1 || messages_delivered == 2 {
3841                 expect_payment_path_successful!(nodes[0]);
3842         }
3843
3844         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3845         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3846         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3847
3848         if messages_delivered > 2 {
3849                 expect_payment_path_successful!(nodes[0]);
3850         }
3851
3852         // Channel should still work fine...
3853         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3854         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3855         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3856 }
3857
3858 #[test]
3859 fn test_drop_messages_peer_disconnect_a() {
3860         do_test_drop_messages_peer_disconnect(0, true);
3861         do_test_drop_messages_peer_disconnect(0, false);
3862         do_test_drop_messages_peer_disconnect(1, false);
3863         do_test_drop_messages_peer_disconnect(2, false);
3864 }
3865
3866 #[test]
3867 fn test_drop_messages_peer_disconnect_b() {
3868         do_test_drop_messages_peer_disconnect(3, false);
3869         do_test_drop_messages_peer_disconnect(4, false);
3870         do_test_drop_messages_peer_disconnect(5, false);
3871         do_test_drop_messages_peer_disconnect(6, false);
3872 }
3873
3874 #[test]
3875 fn test_funding_peer_disconnect() {
3876         // Test that we can lock in our funding tx while disconnected
3877         let chanmon_cfgs = create_chanmon_cfgs(2);
3878         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3879         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3880         let persister: test_utils::TestPersister;
3881         let new_chain_monitor: test_utils::TestChainMonitor;
3882         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3883         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3884         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3885
3886         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3887         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3888
3889         confirm_transaction(&nodes[0], &tx);
3890         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3891         assert!(events_1.is_empty());
3892
3893         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3894
3895         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3896         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3897
3898         confirm_transaction(&nodes[1], &tx);
3899         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3900         assert!(events_2.is_empty());
3901
3902         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3903         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3904         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3905         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3906
3907         // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3908         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3909         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3910         assert_eq!(events_3.len(), 1);
3911         let as_channel_ready = match events_3[0] {
3912                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3913                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3914                         msg.clone()
3915                 },
3916                 _ => panic!("Unexpected event {:?}", events_3[0]),
3917         };
3918
3919         // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3920         // announcement_signatures as well as channel_update.
3921         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3922         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3923         assert_eq!(events_4.len(), 3);
3924         let chan_id;
3925         let bs_channel_ready = match events_4[0] {
3926                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3927                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3928                         chan_id = msg.channel_id;
3929                         msg.clone()
3930                 },
3931                 _ => panic!("Unexpected event {:?}", events_4[0]),
3932         };
3933         let bs_announcement_sigs = match events_4[1] {
3934                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3935                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3936                         msg.clone()
3937                 },
3938                 _ => panic!("Unexpected event {:?}", events_4[1]),
3939         };
3940         match events_4[2] {
3941                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3942                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3943                 },
3944                 _ => panic!("Unexpected event {:?}", events_4[2]),
3945         }
3946
3947         // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3948         // generates a duplicative private channel_update
3949         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3950         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3951         assert_eq!(events_5.len(), 1);
3952         match events_5[0] {
3953                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3954                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3955                 },
3956                 _ => panic!("Unexpected event {:?}", events_5[0]),
3957         };
3958
3959         // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3960         // announcement_signatures.
3961         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3962         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3963         assert_eq!(events_6.len(), 1);
3964         let as_announcement_sigs = match events_6[0] {
3965                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3966                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3967                         msg.clone()
3968                 },
3969                 _ => panic!("Unexpected event {:?}", events_6[0]),
3970         };
3971
3972         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3973         // broadcast the channel announcement globally, as well as re-send its (now-public)
3974         // channel_update.
3975         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3976         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3977         assert_eq!(events_7.len(), 1);
3978         let (chan_announcement, as_update) = match events_7[0] {
3979                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3980                         (msg.clone(), update_msg.clone())
3981                 },
3982                 _ => panic!("Unexpected event {:?}", events_7[0]),
3983         };
3984
3985         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3986         // same channel_announcement.
3987         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3988         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3989         assert_eq!(events_8.len(), 1);
3990         let bs_update = match events_8[0] {
3991                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3992                         assert_eq!(*msg, chan_announcement);
3993                         update_msg.clone()
3994                 },
3995                 _ => panic!("Unexpected event {:?}", events_8[0]),
3996         };
3997
3998         // Provide the channel announcement and public updates to the network graph
3999         nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
4000         nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
4001         nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
4002
4003         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4004         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4005         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
4006
4007         // Check that after deserialization and reconnection we can still generate an identical
4008         // channel_announcement from the cached signatures.
4009         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4010
4011         let nodes_0_serialized = nodes[0].node.encode();
4012         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4013         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4014
4015         persister = test_utils::TestPersister::new();
4016         let keys_manager = &chanmon_cfgs[0].keys_manager;
4017         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);
4018         nodes[0].chain_monitor = &new_chain_monitor;
4019         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4020         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4021                 &mut chan_0_monitor_read, keys_manager).unwrap();
4022         assert!(chan_0_monitor_read.is_empty());
4023
4024         let mut nodes_0_read = &nodes_0_serialized[..];
4025         let (_, nodes_0_deserialized_tmp) = {
4026                 let mut channel_monitors = HashMap::new();
4027                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4028                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4029                         default_config: UserConfig::default(),
4030                         keys_manager,
4031                         fee_estimator: node_cfgs[0].fee_estimator,
4032                         chain_monitor: nodes[0].chain_monitor,
4033                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4034                         logger: nodes[0].logger,
4035                         channel_monitors,
4036                 }).unwrap()
4037         };
4038         nodes_0_deserialized = nodes_0_deserialized_tmp;
4039         assert!(nodes_0_read.is_empty());
4040
4041         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4042         nodes[0].node = &nodes_0_deserialized;
4043         check_added_monitors!(nodes[0], 1);
4044
4045         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4046
4047         // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4048         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4049         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4050         let mut found_announcement = false;
4051         for event in msgs.iter() {
4052                 match event {
4053                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4054                                 if *msg == chan_announcement { found_announcement = true; }
4055                         },
4056                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4057                         _ => panic!("Unexpected event"),
4058                 }
4059         }
4060         assert!(found_announcement);
4061 }
4062
4063 #[test]
4064 fn test_channel_ready_without_best_block_updated() {
4065         // Previously, if we were offline when a funding transaction was locked in, and then we came
4066         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4067         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4068         // channel_ready immediately instead.
4069         let chanmon_cfgs = create_chanmon_cfgs(2);
4070         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4071         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4072         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4073         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4074
4075         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4076
4077         let conf_height = nodes[0].best_block_info().1 + 1;
4078         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4079         let block_txn = [funding_tx];
4080         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4081         let conf_block_header = nodes[0].get_block_header(conf_height);
4082         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4083
4084         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4085         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4086         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4087 }
4088
4089 #[test]
4090 fn test_drop_messages_peer_disconnect_dual_htlc() {
4091         // Test that we can handle reconnecting when both sides of a channel have pending
4092         // commitment_updates when we disconnect.
4093         let chanmon_cfgs = create_chanmon_cfgs(2);
4094         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4095         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4096         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4097         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4098
4099         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4100
4101         // Now try to send a second payment which will fail to send
4102         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4103         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4104         check_added_monitors!(nodes[0], 1);
4105
4106         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4107         assert_eq!(events_1.len(), 1);
4108         match events_1[0] {
4109                 MessageSendEvent::UpdateHTLCs { .. } => {},
4110                 _ => panic!("Unexpected event"),
4111         }
4112
4113         nodes[1].node.claim_funds(payment_preimage_1);
4114         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4115         check_added_monitors!(nodes[1], 1);
4116
4117         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4118         assert_eq!(events_2.len(), 1);
4119         match events_2[0] {
4120                 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 } } => {
4121                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4122                         assert!(update_add_htlcs.is_empty());
4123                         assert_eq!(update_fulfill_htlcs.len(), 1);
4124                         assert!(update_fail_htlcs.is_empty());
4125                         assert!(update_fail_malformed_htlcs.is_empty());
4126                         assert!(update_fee.is_none());
4127
4128                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4129                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4130                         assert_eq!(events_3.len(), 1);
4131                         match events_3[0] {
4132                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4133                                         assert_eq!(*payment_preimage, payment_preimage_1);
4134                                         assert_eq!(*payment_hash, payment_hash_1);
4135                                 },
4136                                 _ => panic!("Unexpected event"),
4137                         }
4138
4139                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4140                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4141                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4142                         check_added_monitors!(nodes[0], 1);
4143                 },
4144                 _ => panic!("Unexpected event"),
4145         }
4146
4147         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4148         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4149
4150         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4151         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4152         assert_eq!(reestablish_1.len(), 1);
4153         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4154         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4155         assert_eq!(reestablish_2.len(), 1);
4156
4157         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4158         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4159         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4160         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4161
4162         assert!(as_resp.0.is_none());
4163         assert!(bs_resp.0.is_none());
4164
4165         assert!(bs_resp.1.is_none());
4166         assert!(bs_resp.2.is_none());
4167
4168         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4169
4170         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4171         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4172         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4173         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4174         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4175         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4176         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4177         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4178         // No commitment_signed so get_event_msg's assert(len == 1) passes
4179         check_added_monitors!(nodes[1], 1);
4180
4181         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4182         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4183         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4184         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4185         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4186         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4187         assert!(bs_second_commitment_signed.update_fee.is_none());
4188         check_added_monitors!(nodes[1], 1);
4189
4190         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4191         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4192         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4193         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4194         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4195         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4196         assert!(as_commitment_signed.update_fee.is_none());
4197         check_added_monitors!(nodes[0], 1);
4198
4199         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4200         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4201         // No commitment_signed so get_event_msg's assert(len == 1) passes
4202         check_added_monitors!(nodes[0], 1);
4203
4204         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4205         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4206         // No commitment_signed so get_event_msg's assert(len == 1) passes
4207         check_added_monitors!(nodes[1], 1);
4208
4209         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4210         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4211         check_added_monitors!(nodes[1], 1);
4212
4213         expect_pending_htlcs_forwardable!(nodes[1]);
4214
4215         let events_5 = nodes[1].node.get_and_clear_pending_events();
4216         assert_eq!(events_5.len(), 1);
4217         match events_5[0] {
4218                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4219                         assert_eq!(payment_hash_2, *payment_hash);
4220                         match &purpose {
4221                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4222                                         assert!(payment_preimage.is_none());
4223                                         assert_eq!(payment_secret_2, *payment_secret);
4224                                 },
4225                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4226                         }
4227                 },
4228                 _ => panic!("Unexpected event"),
4229         }
4230
4231         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4232         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4233         check_added_monitors!(nodes[0], 1);
4234
4235         expect_payment_path_successful!(nodes[0]);
4236         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4237 }
4238
4239 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4240         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4241         // to avoid our counterparty failing the channel.
4242         let chanmon_cfgs = create_chanmon_cfgs(2);
4243         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4244         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4245         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4246
4247         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4248
4249         let our_payment_hash = if send_partial_mpp {
4250                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4251                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4252                 // indicates there are more HTLCs coming.
4253                 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.
4254                 let payment_id = PaymentId([42; 32]);
4255                 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();
4256                 check_added_monitors!(nodes[0], 1);
4257                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4258                 assert_eq!(events.len(), 1);
4259                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4260                 // hop should *not* yet generate any PaymentReceived event(s).
4261                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4262                 our_payment_hash
4263         } else {
4264                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4265         };
4266
4267         let mut block = Block {
4268                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4269                 txdata: vec![],
4270         };
4271         connect_block(&nodes[0], &block);
4272         connect_block(&nodes[1], &block);
4273         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4274         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4275                 block.header.prev_blockhash = block.block_hash();
4276                 connect_block(&nodes[0], &block);
4277                 connect_block(&nodes[1], &block);
4278         }
4279
4280         expect_pending_htlcs_forwardable!(nodes[1]);
4281
4282         check_added_monitors!(nodes[1], 1);
4283         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4284         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4285         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4286         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4287         assert!(htlc_timeout_updates.update_fee.is_none());
4288
4289         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4290         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4291         // 100_000 msat as u64, followed by the height at which we failed back above
4292         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4293         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4294         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4295 }
4296
4297 #[test]
4298 fn test_htlc_timeout() {
4299         do_test_htlc_timeout(true);
4300         do_test_htlc_timeout(false);
4301 }
4302
4303 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4304         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4305         let chanmon_cfgs = create_chanmon_cfgs(3);
4306         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4307         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4308         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4309         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4310         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4311
4312         // Make sure all nodes are at the same starting height
4313         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4314         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4315         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4316
4317         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4318         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4319         {
4320                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4321         }
4322         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4323         check_added_monitors!(nodes[1], 1);
4324
4325         // Now attempt to route a second payment, which should be placed in the holding cell
4326         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4327         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4328         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4329         if forwarded_htlc {
4330                 check_added_monitors!(nodes[0], 1);
4331                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4332                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4333                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4334                 expect_pending_htlcs_forwardable!(nodes[1]);
4335         }
4336         check_added_monitors!(nodes[1], 0);
4337
4338         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4339         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4340         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4341         connect_blocks(&nodes[1], 1);
4342
4343         if forwarded_htlc {
4344                 expect_pending_htlcs_forwardable!(nodes[1]);
4345                 check_added_monitors!(nodes[1], 1);
4346                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4347                 assert_eq!(fail_commit.len(), 1);
4348                 match fail_commit[0] {
4349                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4350                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4351                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4352                         },
4353                         _ => unreachable!(),
4354                 }
4355                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4356         } else {
4357                 let events = nodes[1].node.get_and_clear_pending_events();
4358                 assert_eq!(events.len(), 2);
4359                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4360                         assert_eq!(*payment_hash, second_payment_hash);
4361                 } else { panic!("Unexpected event"); }
4362                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4363                         assert_eq!(*payment_hash, second_payment_hash);
4364                 } else { panic!("Unexpected event"); }
4365         }
4366 }
4367
4368 #[test]
4369 fn test_holding_cell_htlc_add_timeouts() {
4370         do_test_holding_cell_htlc_add_timeouts(false);
4371         do_test_holding_cell_htlc_add_timeouts(true);
4372 }
4373
4374 #[test]
4375 fn test_no_txn_manager_serialize_deserialize() {
4376         let chanmon_cfgs = create_chanmon_cfgs(2);
4377         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4378         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4379         let logger: test_utils::TestLogger;
4380         let fee_estimator: test_utils::TestFeeEstimator;
4381         let persister: test_utils::TestPersister;
4382         let new_chain_monitor: test_utils::TestChainMonitor;
4383         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4384         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4385
4386         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4387
4388         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4389
4390         let nodes_0_serialized = nodes[0].node.encode();
4391         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4392         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4393                 .write(&mut chan_0_monitor_serialized).unwrap();
4394
4395         logger = test_utils::TestLogger::new();
4396         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4397         persister = test_utils::TestPersister::new();
4398         let keys_manager = &chanmon_cfgs[0].keys_manager;
4399         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4400         nodes[0].chain_monitor = &new_chain_monitor;
4401         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4402         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4403                 &mut chan_0_monitor_read, keys_manager).unwrap();
4404         assert!(chan_0_monitor_read.is_empty());
4405
4406         let mut nodes_0_read = &nodes_0_serialized[..];
4407         let config = UserConfig::default();
4408         let (_, nodes_0_deserialized_tmp) = {
4409                 let mut channel_monitors = HashMap::new();
4410                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4411                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4412                         default_config: config,
4413                         keys_manager,
4414                         fee_estimator: &fee_estimator,
4415                         chain_monitor: nodes[0].chain_monitor,
4416                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4417                         logger: &logger,
4418                         channel_monitors,
4419                 }).unwrap()
4420         };
4421         nodes_0_deserialized = nodes_0_deserialized_tmp;
4422         assert!(nodes_0_read.is_empty());
4423
4424         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4425         nodes[0].node = &nodes_0_deserialized;
4426         assert_eq!(nodes[0].node.list_channels().len(), 1);
4427         check_added_monitors!(nodes[0], 1);
4428
4429         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4430         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4431         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4432         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4433
4434         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4435         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4436         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4437         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4438
4439         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4440         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4441         for node in nodes.iter() {
4442                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4443                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4444                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4445         }
4446
4447         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4448 }
4449
4450 #[test]
4451 fn test_manager_serialize_deserialize_events() {
4452         // This test makes sure the events field in ChannelManager survives de/serialization
4453         let chanmon_cfgs = create_chanmon_cfgs(2);
4454         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4455         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4456         let fee_estimator: test_utils::TestFeeEstimator;
4457         let persister: test_utils::TestPersister;
4458         let logger: test_utils::TestLogger;
4459         let new_chain_monitor: test_utils::TestChainMonitor;
4460         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4461         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4462
4463         // Start creating a channel, but stop right before broadcasting the funding transaction
4464         let channel_value = 100000;
4465         let push_msat = 10001;
4466         let a_flags = InitFeatures::known();
4467         let b_flags = InitFeatures::known();
4468         let node_a = nodes.remove(0);
4469         let node_b = nodes.remove(0);
4470         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4471         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()));
4472         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()));
4473
4474         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4475
4476         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4477         check_added_monitors!(node_a, 0);
4478
4479         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()));
4480         {
4481                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4482                 assert_eq!(added_monitors.len(), 1);
4483                 assert_eq!(added_monitors[0].0, funding_output);
4484                 added_monitors.clear();
4485         }
4486
4487         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4488         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4489         {
4490                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4491                 assert_eq!(added_monitors.len(), 1);
4492                 assert_eq!(added_monitors[0].0, funding_output);
4493                 added_monitors.clear();
4494         }
4495         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4496
4497         nodes.push(node_a);
4498         nodes.push(node_b);
4499
4500         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4501         let nodes_0_serialized = nodes[0].node.encode();
4502         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4503         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4504
4505         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4506         logger = test_utils::TestLogger::new();
4507         persister = test_utils::TestPersister::new();
4508         let keys_manager = &chanmon_cfgs[0].keys_manager;
4509         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4510         nodes[0].chain_monitor = &new_chain_monitor;
4511         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4512         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4513                 &mut chan_0_monitor_read, keys_manager).unwrap();
4514         assert!(chan_0_monitor_read.is_empty());
4515
4516         let mut nodes_0_read = &nodes_0_serialized[..];
4517         let config = UserConfig::default();
4518         let (_, nodes_0_deserialized_tmp) = {
4519                 let mut channel_monitors = HashMap::new();
4520                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4521                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4522                         default_config: config,
4523                         keys_manager,
4524                         fee_estimator: &fee_estimator,
4525                         chain_monitor: nodes[0].chain_monitor,
4526                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4527                         logger: &logger,
4528                         channel_monitors,
4529                 }).unwrap()
4530         };
4531         nodes_0_deserialized = nodes_0_deserialized_tmp;
4532         assert!(nodes_0_read.is_empty());
4533
4534         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4535
4536         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4537         nodes[0].node = &nodes_0_deserialized;
4538
4539         // After deserializing, make sure the funding_transaction is still held by the channel manager
4540         let events_4 = nodes[0].node.get_and_clear_pending_events();
4541         assert_eq!(events_4.len(), 0);
4542         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4543         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4544
4545         // Make sure the channel is functioning as though the de/serialization never happened
4546         assert_eq!(nodes[0].node.list_channels().len(), 1);
4547         check_added_monitors!(nodes[0], 1);
4548
4549         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4550         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4551         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4552         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4553
4554         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4555         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4556         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4557         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4558
4559         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4560         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4561         for node in nodes.iter() {
4562                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4563                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4564                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4565         }
4566
4567         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4568 }
4569
4570 #[test]
4571 fn test_simple_manager_serialize_deserialize() {
4572         let chanmon_cfgs = create_chanmon_cfgs(2);
4573         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4574         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4575         let logger: test_utils::TestLogger;
4576         let fee_estimator: test_utils::TestFeeEstimator;
4577         let persister: test_utils::TestPersister;
4578         let new_chain_monitor: test_utils::TestChainMonitor;
4579         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4580         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4581         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4582
4583         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4584         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4585
4586         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4587
4588         let nodes_0_serialized = nodes[0].node.encode();
4589         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4590         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4591
4592         logger = test_utils::TestLogger::new();
4593         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4594         persister = test_utils::TestPersister::new();
4595         let keys_manager = &chanmon_cfgs[0].keys_manager;
4596         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4597         nodes[0].chain_monitor = &new_chain_monitor;
4598         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4599         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4600                 &mut chan_0_monitor_read, keys_manager).unwrap();
4601         assert!(chan_0_monitor_read.is_empty());
4602
4603         let mut nodes_0_read = &nodes_0_serialized[..];
4604         let (_, nodes_0_deserialized_tmp) = {
4605                 let mut channel_monitors = HashMap::new();
4606                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4607                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4608                         default_config: UserConfig::default(),
4609                         keys_manager,
4610                         fee_estimator: &fee_estimator,
4611                         chain_monitor: nodes[0].chain_monitor,
4612                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4613                         logger: &logger,
4614                         channel_monitors,
4615                 }).unwrap()
4616         };
4617         nodes_0_deserialized = nodes_0_deserialized_tmp;
4618         assert!(nodes_0_read.is_empty());
4619
4620         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4621         nodes[0].node = &nodes_0_deserialized;
4622         check_added_monitors!(nodes[0], 1);
4623
4624         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4625
4626         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4627         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4628 }
4629
4630 #[test]
4631 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4632         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4633         let chanmon_cfgs = create_chanmon_cfgs(4);
4634         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4635         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4636         let logger: test_utils::TestLogger;
4637         let fee_estimator: test_utils::TestFeeEstimator;
4638         let persister: test_utils::TestPersister;
4639         let new_chain_monitor: test_utils::TestChainMonitor;
4640         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4641         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4642         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4643         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4644         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4645
4646         let mut node_0_stale_monitors_serialized = Vec::new();
4647         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4648                 let mut writer = test_utils::TestVecWriter(Vec::new());
4649                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4650                 node_0_stale_monitors_serialized.push(writer.0);
4651         }
4652
4653         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4654
4655         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4656         let nodes_0_serialized = nodes[0].node.encode();
4657
4658         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4659         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4660         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4661         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4662
4663         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4664         // nodes[3])
4665         let mut node_0_monitors_serialized = Vec::new();
4666         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4667                 let mut writer = test_utils::TestVecWriter(Vec::new());
4668                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4669                 node_0_monitors_serialized.push(writer.0);
4670         }
4671
4672         logger = test_utils::TestLogger::new();
4673         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4674         persister = test_utils::TestPersister::new();
4675         let keys_manager = &chanmon_cfgs[0].keys_manager;
4676         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4677         nodes[0].chain_monitor = &new_chain_monitor;
4678
4679
4680         let mut node_0_stale_monitors = Vec::new();
4681         for serialized in node_0_stale_monitors_serialized.iter() {
4682                 let mut read = &serialized[..];
4683                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4684                 assert!(read.is_empty());
4685                 node_0_stale_monitors.push(monitor);
4686         }
4687
4688         let mut node_0_monitors = Vec::new();
4689         for serialized in node_0_monitors_serialized.iter() {
4690                 let mut read = &serialized[..];
4691                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4692                 assert!(read.is_empty());
4693                 node_0_monitors.push(monitor);
4694         }
4695
4696         let mut nodes_0_read = &nodes_0_serialized[..];
4697         if let Err(msgs::DecodeError::InvalidValue) =
4698                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4699                 default_config: UserConfig::default(),
4700                 keys_manager,
4701                 fee_estimator: &fee_estimator,
4702                 chain_monitor: nodes[0].chain_monitor,
4703                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4704                 logger: &logger,
4705                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4706         }) { } else {
4707                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4708         };
4709
4710         let mut nodes_0_read = &nodes_0_serialized[..];
4711         let (_, nodes_0_deserialized_tmp) =
4712                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4713                 default_config: UserConfig::default(),
4714                 keys_manager,
4715                 fee_estimator: &fee_estimator,
4716                 chain_monitor: nodes[0].chain_monitor,
4717                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4718                 logger: &logger,
4719                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4720         }).unwrap();
4721         nodes_0_deserialized = nodes_0_deserialized_tmp;
4722         assert!(nodes_0_read.is_empty());
4723
4724         { // Channel close should result in a commitment tx
4725                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4726                 assert_eq!(txn.len(), 1);
4727                 check_spends!(txn[0], funding_tx);
4728                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4729         }
4730
4731         for monitor in node_0_monitors.drain(..) {
4732                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4733                 check_added_monitors!(nodes[0], 1);
4734         }
4735         nodes[0].node = &nodes_0_deserialized;
4736         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4737
4738         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4739         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4740         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4741         //... and we can even still claim the payment!
4742         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4743
4744         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4745         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4746         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4747         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4748         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4749         assert_eq!(msg_events.len(), 1);
4750         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4751                 match action {
4752                         &ErrorAction::SendErrorMessage { ref msg } => {
4753                                 assert_eq!(msg.channel_id, channel_id);
4754                         },
4755                         _ => panic!("Unexpected event!"),
4756                 }
4757         }
4758 }
4759
4760 macro_rules! check_spendable_outputs {
4761         ($node: expr, $keysinterface: expr) => {
4762                 {
4763                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4764                         let mut txn = Vec::new();
4765                         let mut all_outputs = Vec::new();
4766                         let secp_ctx = Secp256k1::new();
4767                         for event in events.drain(..) {
4768                                 match event {
4769                                         Event::SpendableOutputs { mut outputs } => {
4770                                                 for outp in outputs.drain(..) {
4771                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4772                                                         all_outputs.push(outp);
4773                                                 }
4774                                         },
4775                                         _ => panic!("Unexpected event"),
4776                                 };
4777                         }
4778                         if all_outputs.len() > 1 {
4779                                 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) {
4780                                         txn.push(tx);
4781                                 }
4782                         }
4783                         txn
4784                 }
4785         }
4786 }
4787
4788 #[test]
4789 fn test_claim_sizeable_push_msat() {
4790         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4791         let chanmon_cfgs = create_chanmon_cfgs(2);
4792         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4793         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4794         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4795
4796         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4797         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4798         check_closed_broadcast!(nodes[1], true);
4799         check_added_monitors!(nodes[1], 1);
4800         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4801         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4802         assert_eq!(node_txn.len(), 1);
4803         check_spends!(node_txn[0], chan.3);
4804         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
4805
4806         mine_transaction(&nodes[1], &node_txn[0]);
4807         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4808
4809         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4810         assert_eq!(spend_txn.len(), 1);
4811         assert_eq!(spend_txn[0].input.len(), 1);
4812         check_spends!(spend_txn[0], node_txn[0]);
4813         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4814 }
4815
4816 #[test]
4817 fn test_claim_on_remote_sizeable_push_msat() {
4818         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4819         // to_remote output is encumbered by a P2WPKH
4820         let chanmon_cfgs = create_chanmon_cfgs(2);
4821         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4822         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4823         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4824
4825         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4826         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4827         check_closed_broadcast!(nodes[0], true);
4828         check_added_monitors!(nodes[0], 1);
4829         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4830
4831         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4832         assert_eq!(node_txn.len(), 1);
4833         check_spends!(node_txn[0], chan.3);
4834         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
4835
4836         mine_transaction(&nodes[1], &node_txn[0]);
4837         check_closed_broadcast!(nodes[1], true);
4838         check_added_monitors!(nodes[1], 1);
4839         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4840         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4841
4842         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4843         assert_eq!(spend_txn.len(), 1);
4844         check_spends!(spend_txn[0], node_txn[0]);
4845 }
4846
4847 #[test]
4848 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4849         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4850         // to_remote output is encumbered by a P2WPKH
4851
4852         let chanmon_cfgs = create_chanmon_cfgs(2);
4853         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4854         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4855         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4856
4857         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4858         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4859         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4860         assert_eq!(revoked_local_txn[0].input.len(), 1);
4861         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4862
4863         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4864         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4865         check_closed_broadcast!(nodes[1], true);
4866         check_added_monitors!(nodes[1], 1);
4867         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4868
4869         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4870         mine_transaction(&nodes[1], &node_txn[0]);
4871         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4872
4873         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4874         assert_eq!(spend_txn.len(), 3);
4875         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4876         check_spends!(spend_txn[1], node_txn[0]);
4877         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4878 }
4879
4880 #[test]
4881 fn test_static_spendable_outputs_preimage_tx() {
4882         let chanmon_cfgs = create_chanmon_cfgs(2);
4883         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4884         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4885         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4886
4887         // Create some initial channels
4888         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4889
4890         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4891
4892         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4893         assert_eq!(commitment_tx[0].input.len(), 1);
4894         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4895
4896         // Settle A's commitment tx on B's chain
4897         nodes[1].node.claim_funds(payment_preimage);
4898         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4899         check_added_monitors!(nodes[1], 1);
4900         mine_transaction(&nodes[1], &commitment_tx[0]);
4901         check_added_monitors!(nodes[1], 1);
4902         let events = nodes[1].node.get_and_clear_pending_msg_events();
4903         match events[0] {
4904                 MessageSendEvent::UpdateHTLCs { .. } => {},
4905                 _ => panic!("Unexpected event"),
4906         }
4907         match events[1] {
4908                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4909                 _ => panic!("Unexepected event"),
4910         }
4911
4912         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4913         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4914         assert_eq!(node_txn.len(), 3);
4915         check_spends!(node_txn[0], commitment_tx[0]);
4916         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4917         check_spends!(node_txn[1], chan_1.3);
4918         check_spends!(node_txn[2], node_txn[1]);
4919
4920         mine_transaction(&nodes[1], &node_txn[0]);
4921         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4922         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4923
4924         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4925         assert_eq!(spend_txn.len(), 1);
4926         check_spends!(spend_txn[0], node_txn[0]);
4927 }
4928
4929 #[test]
4930 fn test_static_spendable_outputs_timeout_tx() {
4931         let chanmon_cfgs = create_chanmon_cfgs(2);
4932         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4933         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4934         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4935
4936         // Create some initial channels
4937         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4938
4939         // Rebalance the network a bit by relaying one payment through all the channels ...
4940         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4941
4942         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4943
4944         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4945         assert_eq!(commitment_tx[0].input.len(), 1);
4946         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4947
4948         // Settle A's commitment tx on B' chain
4949         mine_transaction(&nodes[1], &commitment_tx[0]);
4950         check_added_monitors!(nodes[1], 1);
4951         let events = nodes[1].node.get_and_clear_pending_msg_events();
4952         match events[0] {
4953                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4954                 _ => panic!("Unexpected event"),
4955         }
4956         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4957
4958         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4959         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4960         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4961         check_spends!(node_txn[0], chan_1.3.clone());
4962         check_spends!(node_txn[1],  commitment_tx[0].clone());
4963         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4964
4965         mine_transaction(&nodes[1], &node_txn[1]);
4966         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4967         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4968         expect_payment_failed!(nodes[1], our_payment_hash, true);
4969
4970         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4971         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4972         check_spends!(spend_txn[0], commitment_tx[0]);
4973         check_spends!(spend_txn[1], node_txn[1]);
4974         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4975 }
4976
4977 #[test]
4978 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4979         let chanmon_cfgs = create_chanmon_cfgs(2);
4980         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4981         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4982         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4983
4984         // Create some initial channels
4985         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4986
4987         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4988         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4989         assert_eq!(revoked_local_txn[0].input.len(), 1);
4990         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4991
4992         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4993
4994         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4995         check_closed_broadcast!(nodes[1], true);
4996         check_added_monitors!(nodes[1], 1);
4997         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4998
4999         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5000         assert_eq!(node_txn.len(), 2);
5001         assert_eq!(node_txn[0].input.len(), 2);
5002         check_spends!(node_txn[0], revoked_local_txn[0]);
5003
5004         mine_transaction(&nodes[1], &node_txn[0]);
5005         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5006
5007         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5008         assert_eq!(spend_txn.len(), 1);
5009         check_spends!(spend_txn[0], node_txn[0]);
5010 }
5011
5012 #[test]
5013 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5014         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5015         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5016         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5017         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5018         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5019
5020         // Create some initial channels
5021         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5022
5023         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5024         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5025         assert_eq!(revoked_local_txn[0].input.len(), 1);
5026         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5027
5028         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5029
5030         // A will generate HTLC-Timeout from revoked commitment tx
5031         mine_transaction(&nodes[0], &revoked_local_txn[0]);
5032         check_closed_broadcast!(nodes[0], true);
5033         check_added_monitors!(nodes[0], 1);
5034         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5035         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5036
5037         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5038         assert_eq!(revoked_htlc_txn.len(), 2);
5039         check_spends!(revoked_htlc_txn[0], chan_1.3);
5040         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5041         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5042         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5043         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5044
5045         // B will generate justice tx from A's revoked commitment/HTLC tx
5046         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5047         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5048         check_closed_broadcast!(nodes[1], true);
5049         check_added_monitors!(nodes[1], 1);
5050         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5051
5052         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5053         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5054         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5055         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5056         // transactions next...
5057         assert_eq!(node_txn[0].input.len(), 3);
5058         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5059
5060         assert_eq!(node_txn[1].input.len(), 2);
5061         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5062         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5063                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5064         } else {
5065                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5066                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5067         }
5068
5069         assert_eq!(node_txn[2].input.len(), 1);
5070         check_spends!(node_txn[2], chan_1.3);
5071
5072         mine_transaction(&nodes[1], &node_txn[1]);
5073         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5074
5075         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5076         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5077         assert_eq!(spend_txn.len(), 1);
5078         assert_eq!(spend_txn[0].input.len(), 1);
5079         check_spends!(spend_txn[0], node_txn[1]);
5080 }
5081
5082 #[test]
5083 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5084         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5085         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5086         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5087         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5088         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5089
5090         // Create some initial channels
5091         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5092
5093         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5094         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5095         assert_eq!(revoked_local_txn[0].input.len(), 1);
5096         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5097
5098         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5099         assert_eq!(revoked_local_txn[0].output.len(), 2);
5100
5101         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5102
5103         // B will generate HTLC-Success from revoked commitment tx
5104         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5105         check_closed_broadcast!(nodes[1], true);
5106         check_added_monitors!(nodes[1], 1);
5107         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5108         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5109
5110         assert_eq!(revoked_htlc_txn.len(), 2);
5111         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5112         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5113         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5114
5115         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5116         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5117         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5118
5119         // A will generate justice tx from B's revoked commitment/HTLC tx
5120         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5121         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5122         check_closed_broadcast!(nodes[0], true);
5123         check_added_monitors!(nodes[0], 1);
5124         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5125
5126         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5127         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5128
5129         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5130         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5131         // transactions next...
5132         assert_eq!(node_txn[0].input.len(), 2);
5133         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5134         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5135                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5136         } else {
5137                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5138                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5139         }
5140
5141         assert_eq!(node_txn[1].input.len(), 1);
5142         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5143
5144         check_spends!(node_txn[2], chan_1.3);
5145
5146         mine_transaction(&nodes[0], &node_txn[1]);
5147         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5148
5149         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5150         // didn't try to generate any new transactions.
5151
5152         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5153         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5154         assert_eq!(spend_txn.len(), 3);
5155         assert_eq!(spend_txn[0].input.len(), 1);
5156         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5157         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5158         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5159         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5160 }
5161
5162 #[test]
5163 fn test_onchain_to_onchain_claim() {
5164         // Test that in case of channel closure, we detect the state of output and claim HTLC
5165         // on downstream peer's remote commitment tx.
5166         // First, have C claim an HTLC against its own latest commitment transaction.
5167         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5168         // channel.
5169         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5170         // gets broadcast.
5171
5172         let chanmon_cfgs = create_chanmon_cfgs(3);
5173         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5174         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5175         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5176
5177         // Create some initial channels
5178         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5179         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5180
5181         // Ensure all nodes are at the same height
5182         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5183         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5184         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5185         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5186
5187         // Rebalance the network a bit by relaying one payment through all the channels ...
5188         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5189         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5190
5191         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5192         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5193         check_spends!(commitment_tx[0], chan_2.3);
5194         nodes[2].node.claim_funds(payment_preimage);
5195         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5196         check_added_monitors!(nodes[2], 1);
5197         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5198         assert!(updates.update_add_htlcs.is_empty());
5199         assert!(updates.update_fail_htlcs.is_empty());
5200         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5201         assert!(updates.update_fail_malformed_htlcs.is_empty());
5202
5203         mine_transaction(&nodes[2], &commitment_tx[0]);
5204         check_closed_broadcast!(nodes[2], true);
5205         check_added_monitors!(nodes[2], 1);
5206         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5207
5208         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5209         assert_eq!(c_txn.len(), 3);
5210         assert_eq!(c_txn[0], c_txn[2]);
5211         assert_eq!(commitment_tx[0], c_txn[1]);
5212         check_spends!(c_txn[1], chan_2.3);
5213         check_spends!(c_txn[2], c_txn[1]);
5214         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5215         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5216         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5217         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5218
5219         // 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
5220         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5221         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5222         check_added_monitors!(nodes[1], 1);
5223         let events = nodes[1].node.get_and_clear_pending_events();
5224         assert_eq!(events.len(), 2);
5225         match events[0] {
5226                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5227                 _ => panic!("Unexpected event"),
5228         }
5229         match events[1] {
5230                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5231                         assert_eq!(fee_earned_msat, Some(1000));
5232                         assert_eq!(prev_channel_id, Some(chan_1.2));
5233                         assert_eq!(claim_from_onchain_tx, true);
5234                         assert_eq!(next_channel_id, Some(chan_2.2));
5235                 },
5236                 _ => panic!("Unexpected event"),
5237         }
5238         {
5239                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5240                 // ChannelMonitor: claim tx
5241                 assert_eq!(b_txn.len(), 1);
5242                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5243                 b_txn.clear();
5244         }
5245         check_added_monitors!(nodes[1], 1);
5246         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5247         assert_eq!(msg_events.len(), 3);
5248         match msg_events[0] {
5249                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5250                 _ => panic!("Unexpected event"),
5251         }
5252         match msg_events[1] {
5253                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5254                 _ => panic!("Unexpected event"),
5255         }
5256         match msg_events[2] {
5257                 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, .. } } => {
5258                         assert!(update_add_htlcs.is_empty());
5259                         assert!(update_fail_htlcs.is_empty());
5260                         assert_eq!(update_fulfill_htlcs.len(), 1);
5261                         assert!(update_fail_malformed_htlcs.is_empty());
5262                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5263                 },
5264                 _ => panic!("Unexpected event"),
5265         };
5266         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5267         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5268         mine_transaction(&nodes[1], &commitment_tx[0]);
5269         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5270         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5271         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5272         assert_eq!(b_txn.len(), 3);
5273         check_spends!(b_txn[1], chan_1.3);
5274         check_spends!(b_txn[2], b_txn[1]);
5275         check_spends!(b_txn[0], commitment_tx[0]);
5276         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5277         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5278         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5279
5280         check_closed_broadcast!(nodes[1], true);
5281         check_added_monitors!(nodes[1], 1);
5282 }
5283
5284 #[test]
5285 fn test_duplicate_payment_hash_one_failure_one_success() {
5286         // Topology : A --> B --> C --> D
5287         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5288         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5289         // we forward one of the payments onwards to D.
5290         let chanmon_cfgs = create_chanmon_cfgs(4);
5291         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5292         // When this test was written, the default base fee floated based on the HTLC count.
5293         // It is now fixed, so we simply set the fee to the expected value here.
5294         let mut config = test_default_channel_config();
5295         config.channel_config.forwarding_fee_base_msat = 196;
5296         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5297                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5298         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5299
5300         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5301         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5302         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5303
5304         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5305         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5306         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5307         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5308         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5309
5310         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5311
5312         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5313         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5314         // script push size limit so that the below script length checks match
5315         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5316         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5317                 .with_features(InvoiceFeatures::known());
5318         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5319         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5320
5321         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5322         assert_eq!(commitment_txn[0].input.len(), 1);
5323         check_spends!(commitment_txn[0], chan_2.3);
5324
5325         mine_transaction(&nodes[1], &commitment_txn[0]);
5326         check_closed_broadcast!(nodes[1], true);
5327         check_added_monitors!(nodes[1], 1);
5328         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5329         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5330
5331         let htlc_timeout_tx;
5332         { // Extract one of the two HTLC-Timeout transaction
5333                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5334                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5335                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5336                 check_spends!(node_txn[0], chan_2.3);
5337
5338                 check_spends!(node_txn[1], commitment_txn[0]);
5339                 assert_eq!(node_txn[1].input.len(), 1);
5340
5341                 if node_txn.len() > 3 {
5342                         check_spends!(node_txn[2], commitment_txn[0]);
5343                         assert_eq!(node_txn[2].input.len(), 1);
5344                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5345
5346                         check_spends!(node_txn[3], commitment_txn[0]);
5347                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5348                 } else {
5349                         check_spends!(node_txn[2], commitment_txn[0]);
5350                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5351                 }
5352
5353                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5354                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5355                 if node_txn.len() > 3 {
5356                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5357                 }
5358                 htlc_timeout_tx = node_txn[1].clone();
5359         }
5360
5361         nodes[2].node.claim_funds(our_payment_preimage);
5362         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5363
5364         mine_transaction(&nodes[2], &commitment_txn[0]);
5365         check_added_monitors!(nodes[2], 2);
5366         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5367         let events = nodes[2].node.get_and_clear_pending_msg_events();
5368         match events[0] {
5369                 MessageSendEvent::UpdateHTLCs { .. } => {},
5370                 _ => panic!("Unexpected event"),
5371         }
5372         match events[1] {
5373                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5374                 _ => panic!("Unexepected event"),
5375         }
5376         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5377         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)
5378         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5379         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5380         assert_eq!(htlc_success_txn[0].input.len(), 1);
5381         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5382         assert_eq!(htlc_success_txn[1].input.len(), 1);
5383         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5384         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5385         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5386         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5387         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5388         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5389
5390         mine_transaction(&nodes[1], &htlc_timeout_tx);
5391         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5392         expect_pending_htlcs_forwardable!(nodes[1]);
5393         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5394         assert!(htlc_updates.update_add_htlcs.is_empty());
5395         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5396         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5397         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5398         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5399         check_added_monitors!(nodes[1], 1);
5400
5401         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5402         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5403         {
5404                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5405         }
5406         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5407
5408         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5409         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5410         // and nodes[2] fee) is rounded down and then claimed in full.
5411         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5412         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5413         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5414         assert!(updates.update_add_htlcs.is_empty());
5415         assert!(updates.update_fail_htlcs.is_empty());
5416         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5417         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5418         assert!(updates.update_fail_malformed_htlcs.is_empty());
5419         check_added_monitors!(nodes[1], 1);
5420
5421         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5422         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5423
5424         let events = nodes[0].node.get_and_clear_pending_events();
5425         match events[0] {
5426                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5427                         assert_eq!(*payment_preimage, our_payment_preimage);
5428                         assert_eq!(*payment_hash, duplicate_payment_hash);
5429                 }
5430                 _ => panic!("Unexpected event"),
5431         }
5432 }
5433
5434 #[test]
5435 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5436         let chanmon_cfgs = create_chanmon_cfgs(2);
5437         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5438         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5439         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5440
5441         // Create some initial channels
5442         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5443
5444         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5445         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5446         assert_eq!(local_txn.len(), 1);
5447         assert_eq!(local_txn[0].input.len(), 1);
5448         check_spends!(local_txn[0], chan_1.3);
5449
5450         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5451         nodes[1].node.claim_funds(payment_preimage);
5452         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5453         check_added_monitors!(nodes[1], 1);
5454
5455         mine_transaction(&nodes[1], &local_txn[0]);
5456         check_added_monitors!(nodes[1], 1);
5457         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5458         let events = nodes[1].node.get_and_clear_pending_msg_events();
5459         match events[0] {
5460                 MessageSendEvent::UpdateHTLCs { .. } => {},
5461                 _ => panic!("Unexpected event"),
5462         }
5463         match events[1] {
5464                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5465                 _ => panic!("Unexepected event"),
5466         }
5467         let node_tx = {
5468                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5469                 assert_eq!(node_txn.len(), 3);
5470                 assert_eq!(node_txn[0], node_txn[2]);
5471                 assert_eq!(node_txn[1], local_txn[0]);
5472                 assert_eq!(node_txn[0].input.len(), 1);
5473                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5474                 check_spends!(node_txn[0], local_txn[0]);
5475                 node_txn[0].clone()
5476         };
5477
5478         mine_transaction(&nodes[1], &node_tx);
5479         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5480
5481         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5482         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5483         assert_eq!(spend_txn.len(), 1);
5484         assert_eq!(spend_txn[0].input.len(), 1);
5485         check_spends!(spend_txn[0], node_tx);
5486         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5487 }
5488
5489 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5490         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5491         // unrevoked commitment transaction.
5492         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5493         // a remote RAA before they could be failed backwards (and combinations thereof).
5494         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5495         // use the same payment hashes.
5496         // Thus, we use a six-node network:
5497         //
5498         // A \         / E
5499         //    - C - D -
5500         // B /         \ F
5501         // And test where C fails back to A/B when D announces its latest commitment transaction
5502         let chanmon_cfgs = create_chanmon_cfgs(6);
5503         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5504         // When this test was written, the default base fee floated based on the HTLC count.
5505         // It is now fixed, so we simply set the fee to the expected value here.
5506         let mut config = test_default_channel_config();
5507         config.channel_config.forwarding_fee_base_msat = 196;
5508         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5509                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5510         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5511
5512         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5513         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5514         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5515         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5516         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5517
5518         // Rebalance and check output sanity...
5519         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5520         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5521         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5522
5523         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5524         // 0th HTLC:
5525         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
5526         // 1st HTLC:
5527         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
5528         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5529         // 2nd HTLC:
5530         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
5531         // 3rd HTLC:
5532         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
5533         // 4th HTLC:
5534         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5535         // 5th HTLC:
5536         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5537         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5538         // 6th HTLC:
5539         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());
5540         // 7th HTLC:
5541         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());
5542
5543         // 8th HTLC:
5544         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5545         // 9th HTLC:
5546         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5547         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
5548
5549         // 10th HTLC:
5550         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
5551         // 11th HTLC:
5552         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5553         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());
5554
5555         // Double-check that six of the new HTLC were added
5556         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5557         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5558         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5559         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5560
5561         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5562         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5563         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5564         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5565         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5566         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5567         check_added_monitors!(nodes[4], 0);
5568         expect_pending_htlcs_forwardable!(nodes[4]);
5569         check_added_monitors!(nodes[4], 1);
5570
5571         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5572         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5573         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5574         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5575         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5576         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5577
5578         // Fail 3rd below-dust and 7th above-dust HTLCs
5579         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5580         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5581         check_added_monitors!(nodes[5], 0);
5582         expect_pending_htlcs_forwardable!(nodes[5]);
5583         check_added_monitors!(nodes[5], 1);
5584
5585         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5586         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5587         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5588         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5589
5590         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5591
5592         expect_pending_htlcs_forwardable!(nodes[3]);
5593         check_added_monitors!(nodes[3], 1);
5594         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5595         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5596         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5597         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5598         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5599         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5600         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5601         if deliver_last_raa {
5602                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5603         } else {
5604                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5605         }
5606
5607         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5608         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5609         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5610         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5611         //
5612         // We now broadcast the latest commitment transaction, which *should* result in failures for
5613         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5614         // the non-broadcast above-dust HTLCs.
5615         //
5616         // Alternatively, we may broadcast the previous commitment transaction, which should only
5617         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5618         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5619
5620         if announce_latest {
5621                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5622         } else {
5623                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5624         }
5625         let events = nodes[2].node.get_and_clear_pending_events();
5626         let close_event = if deliver_last_raa {
5627                 assert_eq!(events.len(), 2);
5628                 events[1].clone()
5629         } else {
5630                 assert_eq!(events.len(), 1);
5631                 events[0].clone()
5632         };
5633         match close_event {
5634                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5635                 _ => panic!("Unexpected event"),
5636         }
5637
5638         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5639         check_closed_broadcast!(nodes[2], true);
5640         if deliver_last_raa {
5641                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5642         } else {
5643                 expect_pending_htlcs_forwardable!(nodes[2]);
5644         }
5645         check_added_monitors!(nodes[2], 3);
5646
5647         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5648         assert_eq!(cs_msgs.len(), 2);
5649         let mut a_done = false;
5650         for msg in cs_msgs {
5651                 match msg {
5652                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5653                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5654                                 // should be failed-backwards here.
5655                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5656                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5657                                         for htlc in &updates.update_fail_htlcs {
5658                                                 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 });
5659                                         }
5660                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5661                                         assert!(!a_done);
5662                                         a_done = true;
5663                                         &nodes[0]
5664                                 } else {
5665                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5666                                         for htlc in &updates.update_fail_htlcs {
5667                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5668                                         }
5669                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5670                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5671                                         &nodes[1]
5672                                 };
5673                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5674                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5675                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5676                                 if announce_latest {
5677                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5678                                         if *node_id == nodes[0].node.get_our_node_id() {
5679                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5680                                         }
5681                                 }
5682                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5683                         },
5684                         _ => panic!("Unexpected event"),
5685                 }
5686         }
5687
5688         let as_events = nodes[0].node.get_and_clear_pending_events();
5689         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5690         let mut as_failds = HashSet::new();
5691         let mut as_updates = 0;
5692         for event in as_events.iter() {
5693                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5694                         assert!(as_failds.insert(*payment_hash));
5695                         if *payment_hash != payment_hash_2 {
5696                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5697                         } else {
5698                                 assert!(!rejected_by_dest);
5699                         }
5700                         if network_update.is_some() {
5701                                 as_updates += 1;
5702                         }
5703                 } else { panic!("Unexpected event"); }
5704         }
5705         assert!(as_failds.contains(&payment_hash_1));
5706         assert!(as_failds.contains(&payment_hash_2));
5707         if announce_latest {
5708                 assert!(as_failds.contains(&payment_hash_3));
5709                 assert!(as_failds.contains(&payment_hash_5));
5710         }
5711         assert!(as_failds.contains(&payment_hash_6));
5712
5713         let bs_events = nodes[1].node.get_and_clear_pending_events();
5714         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5715         let mut bs_failds = HashSet::new();
5716         let mut bs_updates = 0;
5717         for event in bs_events.iter() {
5718                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5719                         assert!(bs_failds.insert(*payment_hash));
5720                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5721                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5722                         } else {
5723                                 assert!(!rejected_by_dest);
5724                         }
5725                         if network_update.is_some() {
5726                                 bs_updates += 1;
5727                         }
5728                 } else { panic!("Unexpected event"); }
5729         }
5730         assert!(bs_failds.contains(&payment_hash_1));
5731         assert!(bs_failds.contains(&payment_hash_2));
5732         if announce_latest {
5733                 assert!(bs_failds.contains(&payment_hash_4));
5734         }
5735         assert!(bs_failds.contains(&payment_hash_5));
5736
5737         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5738         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5739         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5740         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5741         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5742         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5743 }
5744
5745 #[test]
5746 fn test_fail_backwards_latest_remote_announce_a() {
5747         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5748 }
5749
5750 #[test]
5751 fn test_fail_backwards_latest_remote_announce_b() {
5752         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5753 }
5754
5755 #[test]
5756 fn test_fail_backwards_previous_remote_announce() {
5757         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5758         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5759         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5760 }
5761
5762 #[test]
5763 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5764         let chanmon_cfgs = create_chanmon_cfgs(2);
5765         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5766         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5767         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5768
5769         // Create some initial channels
5770         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5771
5772         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5773         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5774         assert_eq!(local_txn[0].input.len(), 1);
5775         check_spends!(local_txn[0], chan_1.3);
5776
5777         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5778         mine_transaction(&nodes[0], &local_txn[0]);
5779         check_closed_broadcast!(nodes[0], true);
5780         check_added_monitors!(nodes[0], 1);
5781         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5782         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5783
5784         let htlc_timeout = {
5785                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5786                 assert_eq!(node_txn.len(), 2);
5787                 check_spends!(node_txn[0], chan_1.3);
5788                 assert_eq!(node_txn[1].input.len(), 1);
5789                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5790                 check_spends!(node_txn[1], local_txn[0]);
5791                 node_txn[1].clone()
5792         };
5793
5794         mine_transaction(&nodes[0], &htlc_timeout);
5795         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5796         expect_payment_failed!(nodes[0], our_payment_hash, true);
5797
5798         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5799         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5800         assert_eq!(spend_txn.len(), 3);
5801         check_spends!(spend_txn[0], local_txn[0]);
5802         assert_eq!(spend_txn[1].input.len(), 1);
5803         check_spends!(spend_txn[1], htlc_timeout);
5804         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5805         assert_eq!(spend_txn[2].input.len(), 2);
5806         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5807         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5808                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5809 }
5810
5811 #[test]
5812 fn test_key_derivation_params() {
5813         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5814         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5815         // let us re-derive the channel key set to then derive a delayed_payment_key.
5816
5817         let chanmon_cfgs = create_chanmon_cfgs(3);
5818
5819         // We manually create the node configuration to backup the seed.
5820         let seed = [42; 32];
5821         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5822         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);
5823         let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5824         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() };
5825         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5826         node_cfgs.remove(0);
5827         node_cfgs.insert(0, node);
5828
5829         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5830         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5831
5832         // Create some initial channels
5833         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5834         // for node 0
5835         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5836         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5837         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5838
5839         // Ensure all nodes are at the same height
5840         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5841         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5842         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5843         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5844
5845         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5846         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5847         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5848         assert_eq!(local_txn_1[0].input.len(), 1);
5849         check_spends!(local_txn_1[0], chan_1.3);
5850
5851         // We check funding pubkey are unique
5852         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]));
5853         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]));
5854         if from_0_funding_key_0 == from_1_funding_key_0
5855             || from_0_funding_key_0 == from_1_funding_key_1
5856             || from_0_funding_key_1 == from_1_funding_key_0
5857             || from_0_funding_key_1 == from_1_funding_key_1 {
5858                 panic!("Funding pubkeys aren't unique");
5859         }
5860
5861         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5862         mine_transaction(&nodes[0], &local_txn_1[0]);
5863         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5864         check_closed_broadcast!(nodes[0], true);
5865         check_added_monitors!(nodes[0], 1);
5866         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5867
5868         let htlc_timeout = {
5869                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5870                 assert_eq!(node_txn[1].input.len(), 1);
5871                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5872                 check_spends!(node_txn[1], local_txn_1[0]);
5873                 node_txn[1].clone()
5874         };
5875
5876         mine_transaction(&nodes[0], &htlc_timeout);
5877         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5878         expect_payment_failed!(nodes[0], our_payment_hash, true);
5879
5880         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5881         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5882         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5883         assert_eq!(spend_txn.len(), 3);
5884         check_spends!(spend_txn[0], local_txn_1[0]);
5885         assert_eq!(spend_txn[1].input.len(), 1);
5886         check_spends!(spend_txn[1], htlc_timeout);
5887         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5888         assert_eq!(spend_txn[2].input.len(), 2);
5889         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5890         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5891                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5892 }
5893
5894 #[test]
5895 fn test_static_output_closing_tx() {
5896         let chanmon_cfgs = create_chanmon_cfgs(2);
5897         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5898         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5899         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5900
5901         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5902
5903         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5904         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5905
5906         mine_transaction(&nodes[0], &closing_tx);
5907         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5908         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5909
5910         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5911         assert_eq!(spend_txn.len(), 1);
5912         check_spends!(spend_txn[0], closing_tx);
5913
5914         mine_transaction(&nodes[1], &closing_tx);
5915         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5916         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5917
5918         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5919         assert_eq!(spend_txn.len(), 1);
5920         check_spends!(spend_txn[0], closing_tx);
5921 }
5922
5923 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5924         let chanmon_cfgs = create_chanmon_cfgs(2);
5925         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5926         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5927         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5928         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5929
5930         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5931
5932         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5933         // present in B's local commitment transaction, but none of A's commitment transactions.
5934         nodes[1].node.claim_funds(payment_preimage);
5935         check_added_monitors!(nodes[1], 1);
5936         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5937
5938         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5939         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5940         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5941
5942         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5943         check_added_monitors!(nodes[0], 1);
5944         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5945         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5946         check_added_monitors!(nodes[1], 1);
5947
5948         let starting_block = nodes[1].best_block_info();
5949         let mut block = Block {
5950                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5951                 txdata: vec![],
5952         };
5953         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5954                 connect_block(&nodes[1], &block);
5955                 block.header.prev_blockhash = block.block_hash();
5956         }
5957         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5958         check_closed_broadcast!(nodes[1], true);
5959         check_added_monitors!(nodes[1], 1);
5960         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5961 }
5962
5963 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5964         let chanmon_cfgs = create_chanmon_cfgs(2);
5965         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5966         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5967         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5968         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5969
5970         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5971         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5972         check_added_monitors!(nodes[0], 1);
5973
5974         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5975
5976         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5977         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5978         // to "time out" the HTLC.
5979
5980         let starting_block = nodes[1].best_block_info();
5981         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5982
5983         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5984                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5985                 header.prev_blockhash = header.block_hash();
5986         }
5987         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5988         check_closed_broadcast!(nodes[0], true);
5989         check_added_monitors!(nodes[0], 1);
5990         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5991 }
5992
5993 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5994         let chanmon_cfgs = create_chanmon_cfgs(3);
5995         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5996         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5997         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5998         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5999
6000         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6001         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6002         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6003         // actually revoked.
6004         let htlc_value = if use_dust { 50000 } else { 3000000 };
6005         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6006         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6007         expect_pending_htlcs_forwardable!(nodes[1]);
6008         check_added_monitors!(nodes[1], 1);
6009
6010         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6011         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6012         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6013         check_added_monitors!(nodes[0], 1);
6014         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6015         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6016         check_added_monitors!(nodes[1], 1);
6017         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6018         check_added_monitors!(nodes[1], 1);
6019         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6020
6021         if check_revoke_no_close {
6022                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6023                 check_added_monitors!(nodes[0], 1);
6024         }
6025
6026         let starting_block = nodes[1].best_block_info();
6027         let mut block = Block {
6028                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6029                 txdata: vec![],
6030         };
6031         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6032                 connect_block(&nodes[0], &block);
6033                 block.header.prev_blockhash = block.block_hash();
6034         }
6035         if !check_revoke_no_close {
6036                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6037                 check_closed_broadcast!(nodes[0], true);
6038                 check_added_monitors!(nodes[0], 1);
6039                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6040         } else {
6041                 let events = nodes[0].node.get_and_clear_pending_events();
6042                 assert_eq!(events.len(), 2);
6043                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6044                         assert_eq!(*payment_hash, our_payment_hash);
6045                 } else { panic!("Unexpected event"); }
6046                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6047                         assert_eq!(*payment_hash, our_payment_hash);
6048                 } else { panic!("Unexpected event"); }
6049         }
6050 }
6051
6052 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6053 // There are only a few cases to test here:
6054 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
6055 //    broadcastable commitment transactions result in channel closure,
6056 //  * its included in an unrevoked-but-previous remote commitment transaction,
6057 //  * its included in the latest remote or local commitment transactions.
6058 // We test each of the three possible commitment transactions individually and use both dust and
6059 // non-dust HTLCs.
6060 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6061 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6062 // tested for at least one of the cases in other tests.
6063 #[test]
6064 fn htlc_claim_single_commitment_only_a() {
6065         do_htlc_claim_local_commitment_only(true);
6066         do_htlc_claim_local_commitment_only(false);
6067
6068         do_htlc_claim_current_remote_commitment_only(true);
6069         do_htlc_claim_current_remote_commitment_only(false);
6070 }
6071
6072 #[test]
6073 fn htlc_claim_single_commitment_only_b() {
6074         do_htlc_claim_previous_remote_commitment_only(true, false);
6075         do_htlc_claim_previous_remote_commitment_only(false, false);
6076         do_htlc_claim_previous_remote_commitment_only(true, true);
6077         do_htlc_claim_previous_remote_commitment_only(false, true);
6078 }
6079
6080 #[test]
6081 #[should_panic]
6082 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6083         let chanmon_cfgs = create_chanmon_cfgs(2);
6084         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6085         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6086         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6087         // Force duplicate randomness for every get-random call
6088         for node in nodes.iter() {
6089                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6090         }
6091
6092         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6093         let channel_value_satoshis=10000;
6094         let push_msat=10001;
6095         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6096         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6097         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6098         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6099
6100         // Create a second channel with the same random values. This used to panic due to a colliding
6101         // channel_id, but now panics due to a colliding outbound SCID alias.
6102         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6103 }
6104
6105 #[test]
6106 fn bolt2_open_channel_sending_node_checks_part2() {
6107         let chanmon_cfgs = create_chanmon_cfgs(2);
6108         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6109         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6110         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6111
6112         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6113         let channel_value_satoshis=2^24;
6114         let push_msat=10001;
6115         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6116
6117         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6118         let channel_value_satoshis=10000;
6119         // Test when push_msat is equal to 1000 * funding_satoshis.
6120         let push_msat=1000*channel_value_satoshis+1;
6121         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6122
6123         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6124         let channel_value_satoshis=10000;
6125         let push_msat=10001;
6126         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
6127         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6128         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6129
6130         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6131         // 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
6132         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6133
6134         // 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.
6135         assert!(BREAKDOWN_TIMEOUT>0);
6136         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6137
6138         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6139         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6140         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6141
6142         // 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.
6143         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6144         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6145         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6146         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6147         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6148 }
6149
6150 #[test]
6151 fn bolt2_open_channel_sane_dust_limit() {
6152         let chanmon_cfgs = create_chanmon_cfgs(2);
6153         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6154         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6155         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6156
6157         let channel_value_satoshis=1000000;
6158         let push_msat=10001;
6159         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6160         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6161         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6162         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6163
6164         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6165         let events = nodes[1].node.get_and_clear_pending_msg_events();
6166         let err_msg = match events[0] {
6167                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6168                         msg.clone()
6169                 },
6170                 _ => panic!("Unexpected event"),
6171         };
6172         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6173 }
6174
6175 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6176 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6177 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6178 // is no longer affordable once it's freed.
6179 #[test]
6180 fn test_fail_holding_cell_htlc_upon_free() {
6181         let chanmon_cfgs = create_chanmon_cfgs(2);
6182         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6183         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6184         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6185         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6186
6187         // First nodes[0] generates an update_fee, setting the channel's
6188         // pending_update_fee.
6189         {
6190                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6191                 *feerate_lock += 20;
6192         }
6193         nodes[0].node.timer_tick_occurred();
6194         check_added_monitors!(nodes[0], 1);
6195
6196         let events = nodes[0].node.get_and_clear_pending_msg_events();
6197         assert_eq!(events.len(), 1);
6198         let (update_msg, commitment_signed) = match events[0] {
6199                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6200                         (update_fee.as_ref(), commitment_signed)
6201                 },
6202                 _ => panic!("Unexpected event"),
6203         };
6204
6205         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6206
6207         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6208         let channel_reserve = chan_stat.channel_reserve_msat;
6209         let feerate = get_feerate!(nodes[0], chan.2);
6210         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6211
6212         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6213         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6214         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6215
6216         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6217         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6218         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6219         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6220
6221         // Flush the pending fee update.
6222         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6223         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6224         check_added_monitors!(nodes[1], 1);
6225         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6226         check_added_monitors!(nodes[0], 1);
6227
6228         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6229         // HTLC, but now that the fee has been raised the payment will now fail, causing
6230         // us to surface its failure to the user.
6231         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6232         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6233         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);
6234         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 {}",
6235                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6236         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6237
6238         // Check that the payment failed to be sent out.
6239         let events = nodes[0].node.get_and_clear_pending_events();
6240         assert_eq!(events.len(), 1);
6241         match &events[0] {
6242                 &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, .. } => {
6243                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6244                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6245                         assert_eq!(*rejected_by_dest, false);
6246                         assert_eq!(*all_paths_failed, true);
6247                         assert_eq!(*network_update, None);
6248                         assert_eq!(*short_channel_id, None);
6249                         assert_eq!(*error_code, None);
6250                         assert_eq!(*error_data, None);
6251                 },
6252                 _ => panic!("Unexpected event"),
6253         }
6254 }
6255
6256 // Test that if multiple HTLCs are released from the holding cell and one is
6257 // valid but the other is no longer valid upon release, the valid HTLC can be
6258 // successfully completed while the other one fails as expected.
6259 #[test]
6260 fn test_free_and_fail_holding_cell_htlcs() {
6261         let chanmon_cfgs = create_chanmon_cfgs(2);
6262         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6263         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6264         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6265         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6266
6267         // First nodes[0] generates an update_fee, setting the channel's
6268         // pending_update_fee.
6269         {
6270                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6271                 *feerate_lock += 200;
6272         }
6273         nodes[0].node.timer_tick_occurred();
6274         check_added_monitors!(nodes[0], 1);
6275
6276         let events = nodes[0].node.get_and_clear_pending_msg_events();
6277         assert_eq!(events.len(), 1);
6278         let (update_msg, commitment_signed) = match events[0] {
6279                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6280                         (update_fee.as_ref(), commitment_signed)
6281                 },
6282                 _ => panic!("Unexpected event"),
6283         };
6284
6285         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6286
6287         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6288         let channel_reserve = chan_stat.channel_reserve_msat;
6289         let feerate = get_feerate!(nodes[0], chan.2);
6290         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6291
6292         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6293         let amt_1 = 20000;
6294         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6295         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6296         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6297
6298         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6299         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6300         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6301         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6302         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6303         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6304         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6305
6306         // Flush the pending fee update.
6307         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6308         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6309         check_added_monitors!(nodes[1], 1);
6310         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6311         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6312         check_added_monitors!(nodes[0], 2);
6313
6314         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6315         // but now that the fee has been raised the second payment will now fail, causing us
6316         // to surface its failure to the user. The first payment should succeed.
6317         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6318         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6319         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", hex::encode(chan.2)), 1);
6320         let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
6321                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6322         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6323
6324         // Check that the second payment failed to be sent out.
6325         let events = nodes[0].node.get_and_clear_pending_events();
6326         assert_eq!(events.len(), 1);
6327         match &events[0] {
6328                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, ref short_channel_id, ref error_code, ref error_data, .. } => {
6329                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6330                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6331                         assert_eq!(*rejected_by_dest, false);
6332                         assert_eq!(*all_paths_failed, true);
6333                         assert_eq!(*network_update, None);
6334                         assert_eq!(*short_channel_id, None);
6335                         assert_eq!(*error_code, None);
6336                         assert_eq!(*error_data, None);
6337                 },
6338                 _ => panic!("Unexpected event"),
6339         }
6340
6341         // Complete the first payment and the RAA from the fee update.
6342         let (payment_event, send_raa_event) = {
6343                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6344                 assert_eq!(msgs.len(), 2);
6345                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6346         };
6347         let raa = match send_raa_event {
6348                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6349                 _ => panic!("Unexpected event"),
6350         };
6351         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6352         check_added_monitors!(nodes[1], 1);
6353         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6354         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6355         let events = nodes[1].node.get_and_clear_pending_events();
6356         assert_eq!(events.len(), 1);
6357         match events[0] {
6358                 Event::PendingHTLCsForwardable { .. } => {},
6359                 _ => panic!("Unexpected event"),
6360         }
6361         nodes[1].node.process_pending_htlc_forwards();
6362         let events = nodes[1].node.get_and_clear_pending_events();
6363         assert_eq!(events.len(), 1);
6364         match events[0] {
6365                 Event::PaymentReceived { .. } => {},
6366                 _ => panic!("Unexpected event"),
6367         }
6368         nodes[1].node.claim_funds(payment_preimage_1);
6369         check_added_monitors!(nodes[1], 1);
6370         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6371
6372         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6373         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6374         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6375         expect_payment_sent!(nodes[0], payment_preimage_1);
6376 }
6377
6378 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6379 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6380 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6381 // once it's freed.
6382 #[test]
6383 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6384         let chanmon_cfgs = create_chanmon_cfgs(3);
6385         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6386         // When this test was written, the default base fee floated based on the HTLC count.
6387         // It is now fixed, so we simply set the fee to the expected value here.
6388         let mut config = test_default_channel_config();
6389         config.channel_config.forwarding_fee_base_msat = 196;
6390         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6391         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6392         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6393         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6394
6395         // First nodes[1] generates an update_fee, setting the channel's
6396         // pending_update_fee.
6397         {
6398                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6399                 *feerate_lock += 20;
6400         }
6401         nodes[1].node.timer_tick_occurred();
6402         check_added_monitors!(nodes[1], 1);
6403
6404         let events = nodes[1].node.get_and_clear_pending_msg_events();
6405         assert_eq!(events.len(), 1);
6406         let (update_msg, commitment_signed) = match events[0] {
6407                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6408                         (update_fee.as_ref(), commitment_signed)
6409                 },
6410                 _ => panic!("Unexpected event"),
6411         };
6412
6413         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6414
6415         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6416         let channel_reserve = chan_stat.channel_reserve_msat;
6417         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6418         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6419
6420         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6421         let feemsat = 239;
6422         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6423         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6424         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6425         let payment_event = {
6426                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6427                 check_added_monitors!(nodes[0], 1);
6428
6429                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6430                 assert_eq!(events.len(), 1);
6431
6432                 SendEvent::from_event(events.remove(0))
6433         };
6434         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6435         check_added_monitors!(nodes[1], 0);
6436         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6437         expect_pending_htlcs_forwardable!(nodes[1]);
6438
6439         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6440         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6441
6442         // Flush the pending fee update.
6443         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6444         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6445         check_added_monitors!(nodes[2], 1);
6446         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6447         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6448         check_added_monitors!(nodes[1], 2);
6449
6450         // A final RAA message is generated to finalize the fee update.
6451         let events = nodes[1].node.get_and_clear_pending_msg_events();
6452         assert_eq!(events.len(), 1);
6453
6454         let raa_msg = match &events[0] {
6455                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6456                         msg.clone()
6457                 },
6458                 _ => panic!("Unexpected event"),
6459         };
6460
6461         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6462         check_added_monitors!(nodes[2], 1);
6463         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6464
6465         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6466         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6467         assert_eq!(process_htlc_forwards_event.len(), 1);
6468         match &process_htlc_forwards_event[0] {
6469                 &Event::PendingHTLCsForwardable { .. } => {},
6470                 _ => panic!("Unexpected event"),
6471         }
6472
6473         // In response, we call ChannelManager's process_pending_htlc_forwards
6474         nodes[1].node.process_pending_htlc_forwards();
6475         check_added_monitors!(nodes[1], 1);
6476
6477         // This causes the HTLC to be failed backwards.
6478         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6479         assert_eq!(fail_event.len(), 1);
6480         let (fail_msg, commitment_signed) = match &fail_event[0] {
6481                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6482                         assert_eq!(updates.update_add_htlcs.len(), 0);
6483                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6484                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6485                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6486                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6487                 },
6488                 _ => panic!("Unexpected event"),
6489         };
6490
6491         // Pass the failure messages back to nodes[0].
6492         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6493         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6494
6495         // Complete the HTLC failure+removal process.
6496         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6497         check_added_monitors!(nodes[0], 1);
6498         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6499         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6500         check_added_monitors!(nodes[1], 2);
6501         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6502         assert_eq!(final_raa_event.len(), 1);
6503         let raa = match &final_raa_event[0] {
6504                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6505                 _ => panic!("Unexpected event"),
6506         };
6507         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6508         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6509         check_added_monitors!(nodes[0], 1);
6510 }
6511
6512 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6513 // 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.
6514 //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.
6515
6516 #[test]
6517 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6518         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6519         let chanmon_cfgs = create_chanmon_cfgs(2);
6520         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6521         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6522         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6523         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6524
6525         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6526         route.paths[0][0].fee_msat = 100;
6527
6528         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6529                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6530         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6531         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6532 }
6533
6534 #[test]
6535 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6536         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6537         let chanmon_cfgs = create_chanmon_cfgs(2);
6538         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6539         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6540         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6541         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6542
6543         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6544         route.paths[0][0].fee_msat = 0;
6545         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6546                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6547
6548         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6549         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6550 }
6551
6552 #[test]
6553 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6554         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6555         let chanmon_cfgs = create_chanmon_cfgs(2);
6556         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6557         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6558         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6559         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6560
6561         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6562         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6563         check_added_monitors!(nodes[0], 1);
6564         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6565         updates.update_add_htlcs[0].amount_msat = 0;
6566
6567         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6568         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6569         check_closed_broadcast!(nodes[1], true).unwrap();
6570         check_added_monitors!(nodes[1], 1);
6571         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6572 }
6573
6574 #[test]
6575 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6576         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6577         //It is enforced when constructing a route.
6578         let chanmon_cfgs = create_chanmon_cfgs(2);
6579         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6580         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6581         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6582         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6583
6584         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6585                 .with_features(InvoiceFeatures::known());
6586         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6587         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6588         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6589                 assert_eq!(err, &"Channel CLTV overflowed?"));
6590 }
6591
6592 #[test]
6593 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6594         //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.
6595         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6596         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6597         let chanmon_cfgs = create_chanmon_cfgs(2);
6598         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6599         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6600         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6601         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6602         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6603
6604         for i in 0..max_accepted_htlcs {
6605                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6606                 let payment_event = {
6607                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6608                         check_added_monitors!(nodes[0], 1);
6609
6610                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6611                         assert_eq!(events.len(), 1);
6612                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6613                                 assert_eq!(htlcs[0].htlc_id, i);
6614                         } else {
6615                                 assert!(false);
6616                         }
6617                         SendEvent::from_event(events.remove(0))
6618                 };
6619                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6620                 check_added_monitors!(nodes[1], 0);
6621                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6622
6623                 expect_pending_htlcs_forwardable!(nodes[1]);
6624                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6625         }
6626         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6627         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6628                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6629
6630         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6631         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6632 }
6633
6634 #[test]
6635 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6636         //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.
6637         let chanmon_cfgs = create_chanmon_cfgs(2);
6638         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6639         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6640         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6641         let channel_value = 100000;
6642         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6643         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6644
6645         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6646
6647         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6648         // Manually create a route over our max in flight (which our router normally automatically
6649         // limits us to.
6650         route.paths[0][0].fee_msat =  max_in_flight + 1;
6651         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6652                 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)));
6653
6654         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6655         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);
6656
6657         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6658 }
6659
6660 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6661 #[test]
6662 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6663         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6664         let chanmon_cfgs = create_chanmon_cfgs(2);
6665         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6666         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6667         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6668         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6669         let htlc_minimum_msat: u64;
6670         {
6671                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6672                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6673                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6674         }
6675
6676         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6677         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6678         check_added_monitors!(nodes[0], 1);
6679         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6680         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6681         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6682         assert!(nodes[1].node.list_channels().is_empty());
6683         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6684         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()));
6685         check_added_monitors!(nodes[1], 1);
6686         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6687 }
6688
6689 #[test]
6690 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6691         //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
6692         let chanmon_cfgs = create_chanmon_cfgs(2);
6693         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6694         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6695         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6696         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6697
6698         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6699         let channel_reserve = chan_stat.channel_reserve_msat;
6700         let feerate = get_feerate!(nodes[0], chan.2);
6701         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6702         // The 2* and +1 are for the fee spike reserve.
6703         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6704
6705         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6706         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6707         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6708         check_added_monitors!(nodes[0], 1);
6709         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6710
6711         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6712         // at this time channel-initiatee receivers are not required to enforce that senders
6713         // respect the fee_spike_reserve.
6714         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6715         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6716
6717         assert!(nodes[1].node.list_channels().is_empty());
6718         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6719         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6720         check_added_monitors!(nodes[1], 1);
6721         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6722 }
6723
6724 #[test]
6725 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6726         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6727         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6728         let chanmon_cfgs = create_chanmon_cfgs(2);
6729         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6730         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6731         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6732         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6733
6734         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6735         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6736         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6737         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6738         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6739         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6740
6741         let mut msg = msgs::UpdateAddHTLC {
6742                 channel_id: chan.2,
6743                 htlc_id: 0,
6744                 amount_msat: 1000,
6745                 payment_hash: our_payment_hash,
6746                 cltv_expiry: htlc_cltv,
6747                 onion_routing_packet: onion_packet.clone(),
6748         };
6749
6750         for i in 0..super::channel::OUR_MAX_HTLCS {
6751                 msg.htlc_id = i as u64;
6752                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6753         }
6754         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6755         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6756
6757         assert!(nodes[1].node.list_channels().is_empty());
6758         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6759         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6760         check_added_monitors!(nodes[1], 1);
6761         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6762 }
6763
6764 #[test]
6765 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6766         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6767         let chanmon_cfgs = create_chanmon_cfgs(2);
6768         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6769         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6770         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6771         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6772
6773         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6774         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6775         check_added_monitors!(nodes[0], 1);
6776         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6777         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6778         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6779
6780         assert!(nodes[1].node.list_channels().is_empty());
6781         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6782         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6783         check_added_monitors!(nodes[1], 1);
6784         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6785 }
6786
6787 #[test]
6788 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6789         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6790         let chanmon_cfgs = create_chanmon_cfgs(2);
6791         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6792         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6793         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6794
6795         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6796         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6797         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6798         check_added_monitors!(nodes[0], 1);
6799         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6800         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6801         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6802
6803         assert!(nodes[1].node.list_channels().is_empty());
6804         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6805         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6806         check_added_monitors!(nodes[1], 1);
6807         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6808 }
6809
6810 #[test]
6811 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6812         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6813         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6814         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6815         let chanmon_cfgs = create_chanmon_cfgs(2);
6816         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6817         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6818         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6819
6820         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6821         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6822         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6823         check_added_monitors!(nodes[0], 1);
6824         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6825         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6826
6827         //Disconnect and Reconnect
6828         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6829         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6830         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6831         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6832         assert_eq!(reestablish_1.len(), 1);
6833         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6834         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6835         assert_eq!(reestablish_2.len(), 1);
6836         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6837         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6838         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6839         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6840
6841         //Resend HTLC
6842         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6843         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6844         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6845         check_added_monitors!(nodes[1], 1);
6846         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6847
6848         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6849
6850         assert!(nodes[1].node.list_channels().is_empty());
6851         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6852         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6853         check_added_monitors!(nodes[1], 1);
6854         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6855 }
6856
6857 #[test]
6858 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6859         //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions:     MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6860
6861         let chanmon_cfgs = create_chanmon_cfgs(2);
6862         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6863         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6864         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6865         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6866         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6867         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6868
6869         check_added_monitors!(nodes[0], 1);
6870         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6871         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6872
6873         let update_msg = msgs::UpdateFulfillHTLC{
6874                 channel_id: chan.2,
6875                 htlc_id: 0,
6876                 payment_preimage: our_payment_preimage,
6877         };
6878
6879         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6880
6881         assert!(nodes[0].node.list_channels().is_empty());
6882         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6883         assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6884         check_added_monitors!(nodes[0], 1);
6885         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6886 }
6887
6888 #[test]
6889 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6890         //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.
6891
6892         let chanmon_cfgs = create_chanmon_cfgs(2);
6893         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6894         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6895         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6896         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6897
6898         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6899         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6900         check_added_monitors!(nodes[0], 1);
6901         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6902         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6903
6904         let update_msg = msgs::UpdateFailHTLC{
6905                 channel_id: chan.2,
6906                 htlc_id: 0,
6907                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6908         };
6909
6910         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6911
6912         assert!(nodes[0].node.list_channels().is_empty());
6913         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6914         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()));
6915         check_added_monitors!(nodes[0], 1);
6916         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6917 }
6918
6919 #[test]
6920 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6921         //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.
6922
6923         let chanmon_cfgs = create_chanmon_cfgs(2);
6924         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6925         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6926         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6927         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6928
6929         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6930         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6931         check_added_monitors!(nodes[0], 1);
6932         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6933         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6934         let update_msg = msgs::UpdateFailMalformedHTLC{
6935                 channel_id: chan.2,
6936                 htlc_id: 0,
6937                 sha256_of_onion: [1; 32],
6938                 failure_code: 0x8000,
6939         };
6940
6941         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6942
6943         assert!(nodes[0].node.list_channels().is_empty());
6944         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6945         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()));
6946         check_added_monitors!(nodes[0], 1);
6947         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6948 }
6949
6950 #[test]
6951 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6952         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6953
6954         let chanmon_cfgs = create_chanmon_cfgs(2);
6955         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6956         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6957         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6958         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6959
6960         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6961
6962         nodes[1].node.claim_funds(our_payment_preimage);
6963         check_added_monitors!(nodes[1], 1);
6964         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6965
6966         let events = nodes[1].node.get_and_clear_pending_msg_events();
6967         assert_eq!(events.len(), 1);
6968         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6969                 match events[0] {
6970                         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, .. } } => {
6971                                 assert!(update_add_htlcs.is_empty());
6972                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6973                                 assert!(update_fail_htlcs.is_empty());
6974                                 assert!(update_fail_malformed_htlcs.is_empty());
6975                                 assert!(update_fee.is_none());
6976                                 update_fulfill_htlcs[0].clone()
6977                         },
6978                         _ => panic!("Unexpected event"),
6979                 }
6980         };
6981
6982         update_fulfill_msg.htlc_id = 1;
6983
6984         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6985
6986         assert!(nodes[0].node.list_channels().is_empty());
6987         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6988         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
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_wrong_preimage() {
6995         //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.
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.payment_preimage = PaymentPreimage([1; 32]);
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!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
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_missing_badonion_bit_for_malformed_htlc_message() {
7038         //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.
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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7044         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7045
7046         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7047         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7048         check_added_monitors!(nodes[0], 1);
7049
7050         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7051         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7052
7053         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7054         check_added_monitors!(nodes[1], 0);
7055         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7056
7057         let events = nodes[1].node.get_and_clear_pending_msg_events();
7058
7059         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7060                 match events[0] {
7061                         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, .. } } => {
7062                                 assert!(update_add_htlcs.is_empty());
7063                                 assert!(update_fulfill_htlcs.is_empty());
7064                                 assert!(update_fail_htlcs.is_empty());
7065                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7066                                 assert!(update_fee.is_none());
7067                                 update_fail_malformed_htlcs[0].clone()
7068                         },
7069                         _ => panic!("Unexpected event"),
7070                 }
7071         };
7072         update_msg.failure_code &= !0x8000;
7073         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7074
7075         assert!(nodes[0].node.list_channels().is_empty());
7076         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7077         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7078         check_added_monitors!(nodes[0], 1);
7079         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7080 }
7081
7082 #[test]
7083 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7084         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7085         //    * 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.
7086
7087         let chanmon_cfgs = create_chanmon_cfgs(3);
7088         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7089         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7090         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7091         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7092         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7093
7094         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7095
7096         //First hop
7097         let mut payment_event = {
7098                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7099                 check_added_monitors!(nodes[0], 1);
7100                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7101                 assert_eq!(events.len(), 1);
7102                 SendEvent::from_event(events.remove(0))
7103         };
7104         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7105         check_added_monitors!(nodes[1], 0);
7106         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7107         expect_pending_htlcs_forwardable!(nodes[1]);
7108         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7109         assert_eq!(events_2.len(), 1);
7110         check_added_monitors!(nodes[1], 1);
7111         payment_event = SendEvent::from_event(events_2.remove(0));
7112         assert_eq!(payment_event.msgs.len(), 1);
7113
7114         //Second Hop
7115         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7116         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7117         check_added_monitors!(nodes[2], 0);
7118         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7119
7120         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7121         assert_eq!(events_3.len(), 1);
7122         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7123                 match events_3[0] {
7124                         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 } } => {
7125                                 assert!(update_add_htlcs.is_empty());
7126                                 assert!(update_fulfill_htlcs.is_empty());
7127                                 assert!(update_fail_htlcs.is_empty());
7128                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7129                                 assert!(update_fee.is_none());
7130                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7131                         },
7132                         _ => panic!("Unexpected event"),
7133                 }
7134         };
7135
7136         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7137
7138         check_added_monitors!(nodes[1], 0);
7139         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7140         expect_pending_htlcs_forwardable!(nodes[1]);
7141         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7142         assert_eq!(events_4.len(), 1);
7143
7144         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7145         match events_4[0] {
7146                 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, .. } } => {
7147                         assert!(update_add_htlcs.is_empty());
7148                         assert!(update_fulfill_htlcs.is_empty());
7149                         assert_eq!(update_fail_htlcs.len(), 1);
7150                         assert!(update_fail_malformed_htlcs.is_empty());
7151                         assert!(update_fee.is_none());
7152                 },
7153                 _ => panic!("Unexpected event"),
7154         };
7155
7156         check_added_monitors!(nodes[1], 1);
7157 }
7158
7159 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7160         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7161         // 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
7162         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7163
7164         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7165         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7166         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7167         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7168         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7169         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7170
7171         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7172
7173         // We route 2 dust-HTLCs between A and B
7174         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7175         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7176         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7177
7178         // Cache one local commitment tx as previous
7179         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7180
7181         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7182         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7183         check_added_monitors!(nodes[1], 0);
7184         expect_pending_htlcs_forwardable!(nodes[1]);
7185         check_added_monitors!(nodes[1], 1);
7186
7187         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7188         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7189         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7190         check_added_monitors!(nodes[0], 1);
7191
7192         // Cache one local commitment tx as lastest
7193         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7194
7195         let events = nodes[0].node.get_and_clear_pending_msg_events();
7196         match events[0] {
7197                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7198                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7199                 },
7200                 _ => panic!("Unexpected event"),
7201         }
7202         match events[1] {
7203                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7204                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7205                 },
7206                 _ => panic!("Unexpected event"),
7207         }
7208
7209         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7210         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7211         if announce_latest {
7212                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7213         } else {
7214                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7215         }
7216
7217         check_closed_broadcast!(nodes[0], true);
7218         check_added_monitors!(nodes[0], 1);
7219         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7220
7221         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7222         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7223         let events = nodes[0].node.get_and_clear_pending_events();
7224         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7225         assert_eq!(events.len(), 2);
7226         let mut first_failed = false;
7227         for event in events {
7228                 match event {
7229                         Event::PaymentPathFailed { payment_hash, .. } => {
7230                                 if payment_hash == payment_hash_1 {
7231                                         assert!(!first_failed);
7232                                         first_failed = true;
7233                                 } else {
7234                                         assert_eq!(payment_hash, payment_hash_2);
7235                                 }
7236                         }
7237                         _ => panic!("Unexpected event"),
7238                 }
7239         }
7240 }
7241
7242 #[test]
7243 fn test_failure_delay_dust_htlc_local_commitment() {
7244         do_test_failure_delay_dust_htlc_local_commitment(true);
7245         do_test_failure_delay_dust_htlc_local_commitment(false);
7246 }
7247
7248 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7249         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7250         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7251         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7252         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7253         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7254         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7255
7256         let chanmon_cfgs = create_chanmon_cfgs(3);
7257         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7258         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7259         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7260         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7261
7262         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7263
7264         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7265         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7266
7267         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7268         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7269
7270         // We revoked bs_commitment_tx
7271         if revoked {
7272                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7273                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7274         }
7275
7276         let mut timeout_tx = Vec::new();
7277         if local {
7278                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7279                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7280                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7281                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7282                 expect_payment_failed!(nodes[0], dust_hash, true);
7283
7284                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7285                 check_closed_broadcast!(nodes[0], true);
7286                 check_added_monitors!(nodes[0], 1);
7287                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7288                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7289                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7290                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7291                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7292                 mine_transaction(&nodes[0], &timeout_tx[0]);
7293                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7294                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7295         } else {
7296                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7297                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7298                 check_closed_broadcast!(nodes[0], true);
7299                 check_added_monitors!(nodes[0], 1);
7300                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7301                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7302
7303                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7304                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7305                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7306                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7307                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7308                 // dust HTLC should have been failed.
7309                 expect_payment_failed!(nodes[0], dust_hash, true);
7310
7311                 if !revoked {
7312                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7313                 } else {
7314                         assert_eq!(timeout_tx[0].lock_time, 0);
7315                 }
7316                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7317                 mine_transaction(&nodes[0], &timeout_tx[0]);
7318                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7319                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7320                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7321         }
7322 }
7323
7324 #[test]
7325 fn test_sweep_outbound_htlc_failure_update() {
7326         do_test_sweep_outbound_htlc_failure_update(false, true);
7327         do_test_sweep_outbound_htlc_failure_update(false, false);
7328         do_test_sweep_outbound_htlc_failure_update(true, false);
7329 }
7330
7331 #[test]
7332 fn test_user_configurable_csv_delay() {
7333         // We test our channel constructors yield errors when we pass them absurd csv delay
7334
7335         let mut low_our_to_self_config = UserConfig::default();
7336         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7337         let mut high_their_to_self_config = UserConfig::default();
7338         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7339         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7340         let chanmon_cfgs = create_chanmon_cfgs(2);
7341         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7342         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7343         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7344
7345         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7346         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7347                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7348                 &low_our_to_self_config, 0, 42)
7349         {
7350                 match error {
7351                         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())); },
7352                         _ => panic!("Unexpected event"),
7353                 }
7354         } else { assert!(false) }
7355
7356         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7357         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7358         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7359         open_channel.to_self_delay = 200;
7360         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7361                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7362                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7363         {
7364                 match error {
7365                         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()));  },
7366                         _ => panic!("Unexpected event"),
7367                 }
7368         } else { assert!(false); }
7369
7370         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7371         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7372         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()));
7373         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7374         accept_channel.to_self_delay = 200;
7375         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7376         let reason_msg;
7377         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7378                 match action {
7379                         &ErrorAction::SendErrorMessage { ref msg } => {
7380                                 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()));
7381                                 reason_msg = msg.data.clone();
7382                         },
7383                         _ => { panic!(); }
7384                 }
7385         } else { panic!(); }
7386         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7387
7388         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7389         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7390         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7391         open_channel.to_self_delay = 200;
7392         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7393                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7394                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7395         {
7396                 match error {
7397                         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())); },
7398                         _ => panic!("Unexpected event"),
7399                 }
7400         } else { assert!(false); }
7401 }
7402
7403 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7404         // When we get a data_loss_protect proving we're behind, we immediately panic as the
7405         // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7406         // panic message informs the user they should force-close without broadcasting, which is tested
7407         // if `reconnect_panicing` is not set.
7408         let persister;
7409         let logger;
7410         let fee_estimator;
7411         let tx_broadcaster;
7412         let chain_source;
7413         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7414         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7415         // during signing due to revoked tx
7416         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7417         let keys_manager = &chanmon_cfgs[0].keys_manager;
7418         let monitor;
7419         let node_state_0;
7420         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7421         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7422         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7423
7424         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7425
7426         // Cache node A state before any channel update
7427         let previous_node_state = nodes[0].node.encode();
7428         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7429         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7430
7431         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7432         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7433
7434         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7435         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7436
7437         // Restore node A from previous state
7438         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7439         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7440         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7441         tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7442         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7443         persister = test_utils::TestPersister::new();
7444         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7445         node_state_0 = {
7446                 let mut channel_monitors = HashMap::new();
7447                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7448                 <(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 {
7449                         keys_manager: keys_manager,
7450                         fee_estimator: &fee_estimator,
7451                         chain_monitor: &monitor,
7452                         logger: &logger,
7453                         tx_broadcaster: &tx_broadcaster,
7454                         default_config: UserConfig::default(),
7455                         channel_monitors,
7456                 }).unwrap().1
7457         };
7458         nodes[0].node = &node_state_0;
7459         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7460         nodes[0].chain_monitor = &monitor;
7461         nodes[0].chain_source = &chain_source;
7462
7463         check_added_monitors!(nodes[0], 1);
7464
7465         if reconnect_panicing {
7466                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7467                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7468
7469                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7470
7471                 // Check we close channel detecting A is fallen-behind
7472                 // Check that we sent the warning message when we detected that A has fallen behind,
7473                 // and give the possibility for A to recover from the warning.
7474                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7475                 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7476                 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7477
7478                 {
7479                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7480                         // The node B should not broadcast the transaction to force close the channel!
7481                         assert!(node_txn.is_empty());
7482                 }
7483
7484                 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7485                 // Check A panics upon seeing proof it has fallen behind.
7486                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7487                 return; // By this point we should have panic'ed!
7488         }
7489
7490         nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7491         check_added_monitors!(nodes[0], 1);
7492         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7493         {
7494                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7495                 assert_eq!(node_txn.len(), 0);
7496         }
7497
7498         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7499                 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7500                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7501                         match action {
7502                                 &ErrorAction::SendErrorMessage { ref msg } => {
7503                                         assert_eq!(msg.data, "Channel force-closed");
7504                                 },
7505                                 _ => panic!("Unexpected event!"),
7506                         }
7507                 } else {
7508                         panic!("Unexpected event {:?}", msg)
7509                 }
7510         }
7511
7512         // after the warning message sent by B, we should not able to
7513         // use the channel, or reconnect with success to the channel.
7514         assert!(nodes[0].node.list_usable_channels().is_empty());
7515         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7516         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7517         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7518
7519         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7520         let mut err_msgs_0 = Vec::with_capacity(1);
7521         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7522                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7523                         match action {
7524                                 &ErrorAction::SendErrorMessage { ref msg } => {
7525                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7526                                         err_msgs_0.push(msg.clone());
7527                                 },
7528                                 _ => panic!("Unexpected event!"),
7529                         }
7530                 } else {
7531                         panic!("Unexpected event!");
7532                 }
7533         }
7534         assert_eq!(err_msgs_0.len(), 1);
7535         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7536         assert!(nodes[1].node.list_usable_channels().is_empty());
7537         check_added_monitors!(nodes[1], 1);
7538         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7539         check_closed_broadcast!(nodes[1], false);
7540 }
7541
7542 #[test]
7543 #[should_panic]
7544 fn test_data_loss_protect_showing_stale_state_panics() {
7545         do_test_data_loss_protect(true);
7546 }
7547
7548 #[test]
7549 fn test_force_close_without_broadcast() {
7550         do_test_data_loss_protect(false);
7551 }
7552
7553 #[test]
7554 fn test_check_htlc_underpaying() {
7555         // Send payment through A -> B but A is maliciously
7556         // sending a probe payment (i.e less than expected value0
7557         // to B, B should refuse payment.
7558
7559         let chanmon_cfgs = create_chanmon_cfgs(2);
7560         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7561         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7562         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7563
7564         // Create some initial channels
7565         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7566
7567         let scorer = test_utils::TestScorer::with_penalty(0);
7568         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7569         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7570         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();
7571         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7572         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7573         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7574         check_added_monitors!(nodes[0], 1);
7575
7576         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7577         assert_eq!(events.len(), 1);
7578         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7579         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7580         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7581
7582         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7583         // and then will wait a second random delay before failing the HTLC back:
7584         expect_pending_htlcs_forwardable!(nodes[1]);
7585         expect_pending_htlcs_forwardable!(nodes[1]);
7586
7587         // Node 3 is expecting payment of 100_000 but received 10_000,
7588         // it should fail htlc like we didn't know the preimage.
7589         nodes[1].node.process_pending_htlc_forwards();
7590
7591         let events = nodes[1].node.get_and_clear_pending_msg_events();
7592         assert_eq!(events.len(), 1);
7593         let (update_fail_htlc, commitment_signed) = match events[0] {
7594                 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 } } => {
7595                         assert!(update_add_htlcs.is_empty());
7596                         assert!(update_fulfill_htlcs.is_empty());
7597                         assert_eq!(update_fail_htlcs.len(), 1);
7598                         assert!(update_fail_malformed_htlcs.is_empty());
7599                         assert!(update_fee.is_none());
7600                         (update_fail_htlcs[0].clone(), commitment_signed)
7601                 },
7602                 _ => panic!("Unexpected event"),
7603         };
7604         check_added_monitors!(nodes[1], 1);
7605
7606         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7607         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7608
7609         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7610         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7611         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7612         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7613 }
7614
7615 #[test]
7616 fn test_announce_disable_channels() {
7617         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7618         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7619
7620         let chanmon_cfgs = create_chanmon_cfgs(2);
7621         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7622         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7623         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7624
7625         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7626         create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7627         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7628
7629         // Disconnect peers
7630         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7631         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7632
7633         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7634         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7635         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7636         assert_eq!(msg_events.len(), 3);
7637         let mut chans_disabled = HashMap::new();
7638         for e in msg_events {
7639                 match e {
7640                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7641                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7642                                 // Check that each channel gets updated exactly once
7643                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7644                                         panic!("Generated ChannelUpdate for wrong chan!");
7645                                 }
7646                         },
7647                         _ => panic!("Unexpected event"),
7648                 }
7649         }
7650         // Reconnect peers
7651         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7652         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7653         assert_eq!(reestablish_1.len(), 3);
7654         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7655         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7656         assert_eq!(reestablish_2.len(), 3);
7657
7658         // Reestablish chan_1
7659         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7660         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7661         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7662         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7663         // Reestablish chan_2
7664         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7665         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7666         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7667         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7668         // Reestablish chan_3
7669         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7670         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7671         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7672         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7673
7674         nodes[0].node.timer_tick_occurred();
7675         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7676         nodes[0].node.timer_tick_occurred();
7677         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7678         assert_eq!(msg_events.len(), 3);
7679         for e in msg_events {
7680                 match e {
7681                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7682                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7683                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7684                                         // Each update should have a higher timestamp than the previous one, replacing
7685                                         // the old one.
7686                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7687                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7688                                 }
7689                         },
7690                         _ => panic!("Unexpected event"),
7691                 }
7692         }
7693         // Check that each channel gets updated exactly once
7694         assert!(chans_disabled.is_empty());
7695 }
7696
7697 #[test]
7698 fn test_bump_penalty_txn_on_revoked_commitment() {
7699         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7700         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7701
7702         let chanmon_cfgs = create_chanmon_cfgs(2);
7703         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7704         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7705         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7706
7707         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7708
7709         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7710         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7711                 .with_features(InvoiceFeatures::known());
7712         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7713         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7714
7715         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7716         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7717         assert_eq!(revoked_txn[0].output.len(), 4);
7718         assert_eq!(revoked_txn[0].input.len(), 1);
7719         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7720         let revoked_txid = revoked_txn[0].txid();
7721
7722         let mut penalty_sum = 0;
7723         for outp in revoked_txn[0].output.iter() {
7724                 if outp.script_pubkey.is_v0_p2wsh() {
7725                         penalty_sum += outp.value;
7726                 }
7727         }
7728
7729         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7730         let header_114 = connect_blocks(&nodes[1], 14);
7731
7732         // Actually revoke tx by claiming a HTLC
7733         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7734         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7735         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7736         check_added_monitors!(nodes[1], 1);
7737
7738         // One or more justice tx should have been broadcast, check it
7739         let penalty_1;
7740         let feerate_1;
7741         {
7742                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7743                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7744                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7745                 assert_eq!(node_txn[0].output.len(), 1);
7746                 check_spends!(node_txn[0], revoked_txn[0]);
7747                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7748                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7749                 penalty_1 = node_txn[0].txid();
7750                 node_txn.clear();
7751         };
7752
7753         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7754         connect_blocks(&nodes[1], 15);
7755         let mut penalty_2 = penalty_1;
7756         let mut feerate_2 = 0;
7757         {
7758                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7759                 assert_eq!(node_txn.len(), 1);
7760                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7761                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7762                         assert_eq!(node_txn[0].output.len(), 1);
7763                         check_spends!(node_txn[0], revoked_txn[0]);
7764                         penalty_2 = node_txn[0].txid();
7765                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7766                         assert_ne!(penalty_2, penalty_1);
7767                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7768                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7769                         // Verify 25% bump heuristic
7770                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7771                         node_txn.clear();
7772                 }
7773         }
7774         assert_ne!(feerate_2, 0);
7775
7776         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7777         connect_blocks(&nodes[1], 1);
7778         let penalty_3;
7779         let mut feerate_3 = 0;
7780         {
7781                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7782                 assert_eq!(node_txn.len(), 1);
7783                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7784                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7785                         assert_eq!(node_txn[0].output.len(), 1);
7786                         check_spends!(node_txn[0], revoked_txn[0]);
7787                         penalty_3 = node_txn[0].txid();
7788                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7789                         assert_ne!(penalty_3, penalty_2);
7790                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7791                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7792                         // Verify 25% bump heuristic
7793                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7794                         node_txn.clear();
7795                 }
7796         }
7797         assert_ne!(feerate_3, 0);
7798
7799         nodes[1].node.get_and_clear_pending_events();
7800         nodes[1].node.get_and_clear_pending_msg_events();
7801 }
7802
7803 #[test]
7804 fn test_bump_penalty_txn_on_revoked_htlcs() {
7805         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7806         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7807
7808         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7809         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7810         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7811         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7812         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7813
7814         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7815         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7816         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7817         let scorer = test_utils::TestScorer::with_penalty(0);
7818         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7819         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7820                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7821         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7822         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7823         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7824                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7825         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7826
7827         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7828         assert_eq!(revoked_local_txn[0].input.len(), 1);
7829         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7830
7831         // Revoke local commitment tx
7832         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7833
7834         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7835         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7836         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7837         check_closed_broadcast!(nodes[1], true);
7838         check_added_monitors!(nodes[1], 1);
7839         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7840         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7841
7842         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7843         assert_eq!(revoked_htlc_txn.len(), 3);
7844         check_spends!(revoked_htlc_txn[1], chan.3);
7845
7846         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7847         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7848         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7849
7850         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7851         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7852         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7853         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7854
7855         // Broadcast set of revoked txn on A
7856         let hash_128 = connect_blocks(&nodes[0], 40);
7857         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7858         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7859         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7860         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7861         let events = nodes[0].node.get_and_clear_pending_events();
7862         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7863         match events[1] {
7864                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7865                 _ => panic!("Unexpected event"),
7866         }
7867         let first;
7868         let feerate_1;
7869         let penalty_txn;
7870         {
7871                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7872                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7873                 // Verify claim tx are spending revoked HTLC txn
7874
7875                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7876                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7877                 // which are included in the same block (they are broadcasted because we scan the
7878                 // transactions linearly and generate claims as we go, they likely should be removed in the
7879                 // future).
7880                 assert_eq!(node_txn[0].input.len(), 1);
7881                 check_spends!(node_txn[0], revoked_local_txn[0]);
7882                 assert_eq!(node_txn[1].input.len(), 1);
7883                 check_spends!(node_txn[1], revoked_local_txn[0]);
7884                 assert_eq!(node_txn[2].input.len(), 1);
7885                 check_spends!(node_txn[2], revoked_local_txn[0]);
7886
7887                 // Each of the three justice transactions claim a separate (single) output of the three
7888                 // available, which we check here:
7889                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7890                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7891                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7892
7893                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7894                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7895
7896                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7897                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7898                 // a remote commitment tx has already been confirmed).
7899                 check_spends!(node_txn[3], chan.3);
7900
7901                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7902                 // output, checked above).
7903                 assert_eq!(node_txn[4].input.len(), 2);
7904                 assert_eq!(node_txn[4].output.len(), 1);
7905                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7906
7907                 first = node_txn[4].txid();
7908                 // Store both feerates for later comparison
7909                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7910                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7911                 penalty_txn = vec![node_txn[2].clone()];
7912                 node_txn.clear();
7913         }
7914
7915         // Connect one more block to see if bumped penalty are issued for HTLC txn
7916         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7917         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7918         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7919         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7920         {
7921                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7922                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7923
7924                 check_spends!(node_txn[0], revoked_local_txn[0]);
7925                 check_spends!(node_txn[1], revoked_local_txn[0]);
7926                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7927                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7928                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7929                 } else {
7930                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7931                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7932                 }
7933
7934                 node_txn.clear();
7935         };
7936
7937         // Few more blocks to confirm penalty txn
7938         connect_blocks(&nodes[0], 4);
7939         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7940         let header_144 = connect_blocks(&nodes[0], 9);
7941         let node_txn = {
7942                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7943                 assert_eq!(node_txn.len(), 1);
7944
7945                 assert_eq!(node_txn[0].input.len(), 2);
7946                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7947                 // Verify bumped tx is different and 25% bump heuristic
7948                 assert_ne!(first, node_txn[0].txid());
7949                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7950                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7951                 assert!(feerate_2 * 100 > feerate_1 * 125);
7952                 let txn = vec![node_txn[0].clone()];
7953                 node_txn.clear();
7954                 txn
7955         };
7956         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7957         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7958         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7959         connect_blocks(&nodes[0], 20);
7960         {
7961                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7962                 // We verify than no new transaction has been broadcast because previously
7963                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7964                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7965                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7966                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7967                 // up bumped justice generation.
7968                 assert_eq!(node_txn.len(), 0);
7969                 node_txn.clear();
7970         }
7971         check_closed_broadcast!(nodes[0], true);
7972         check_added_monitors!(nodes[0], 1);
7973 }
7974
7975 #[test]
7976 fn test_bump_penalty_txn_on_remote_commitment() {
7977         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7978         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7979
7980         // Create 2 HTLCs
7981         // Provide preimage for one
7982         // Check aggregation
7983
7984         let chanmon_cfgs = create_chanmon_cfgs(2);
7985         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7986         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7987         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7988
7989         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7990         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7991         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7992
7993         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7994         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7995         assert_eq!(remote_txn[0].output.len(), 4);
7996         assert_eq!(remote_txn[0].input.len(), 1);
7997         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7998
7999         // Claim a HTLC without revocation (provide B monitor with preimage)
8000         nodes[1].node.claim_funds(payment_preimage);
8001         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
8002         mine_transaction(&nodes[1], &remote_txn[0]);
8003         check_added_monitors!(nodes[1], 2);
8004         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8005
8006         // One or more claim tx should have been broadcast, check it
8007         let timeout;
8008         let preimage;
8009         let preimage_bump;
8010         let feerate_timeout;
8011         let feerate_preimage;
8012         {
8013                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8014                 // 9 transactions including:
8015                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8016                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8017                 // 2 * HTLC-Success (one RBF bump we'll check later)
8018                 // 1 * HTLC-Timeout
8019                 assert_eq!(node_txn.len(), 8);
8020                 assert_eq!(node_txn[0].input.len(), 1);
8021                 assert_eq!(node_txn[6].input.len(), 1);
8022                 check_spends!(node_txn[0], remote_txn[0]);
8023                 check_spends!(node_txn[6], remote_txn[0]);
8024
8025                 check_spends!(node_txn[1], chan.3);
8026                 check_spends!(node_txn[2], node_txn[1]);
8027
8028                 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
8029                         preimage_bump = node_txn[3].clone();
8030                         check_spends!(node_txn[3], remote_txn[0]);
8031
8032                         assert_eq!(node_txn[1], node_txn[4]);
8033                         assert_eq!(node_txn[2], node_txn[5]);
8034                 } else {
8035                         preimage_bump = node_txn[7].clone();
8036                         check_spends!(node_txn[7], remote_txn[0]);
8037                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8038
8039                         assert_eq!(node_txn[1], node_txn[3]);
8040                         assert_eq!(node_txn[2], node_txn[4]);
8041                 }
8042
8043                 timeout = node_txn[6].txid();
8044                 let index = node_txn[6].input[0].previous_output.vout;
8045                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8046                 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8047
8048                 preimage = node_txn[0].txid();
8049                 let index = node_txn[0].input[0].previous_output.vout;
8050                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8051                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8052
8053                 node_txn.clear();
8054         };
8055         assert_ne!(feerate_timeout, 0);
8056         assert_ne!(feerate_preimage, 0);
8057
8058         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8059         connect_blocks(&nodes[1], 15);
8060         {
8061                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8062                 assert_eq!(node_txn.len(), 1);
8063                 assert_eq!(node_txn[0].input.len(), 1);
8064                 assert_eq!(preimage_bump.input.len(), 1);
8065                 check_spends!(node_txn[0], remote_txn[0]);
8066                 check_spends!(preimage_bump, remote_txn[0]);
8067
8068                 let index = preimage_bump.input[0].previous_output.vout;
8069                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8070                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8071                 assert!(new_feerate * 100 > feerate_timeout * 125);
8072                 assert_ne!(timeout, preimage_bump.txid());
8073
8074                 let index = node_txn[0].input[0].previous_output.vout;
8075                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8076                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8077                 assert!(new_feerate * 100 > feerate_preimage * 125);
8078                 assert_ne!(preimage, node_txn[0].txid());
8079
8080                 node_txn.clear();
8081         }
8082
8083         nodes[1].node.get_and_clear_pending_events();
8084         nodes[1].node.get_and_clear_pending_msg_events();
8085 }
8086
8087 #[test]
8088 fn test_counterparty_raa_skip_no_crash() {
8089         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8090         // commitment transaction, we would have happily carried on and provided them the next
8091         // commitment transaction based on one RAA forward. This would probably eventually have led to
8092         // channel closure, but it would not have resulted in funds loss. Still, our
8093         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8094         // check simply that the channel is closed in response to such an RAA, but don't check whether
8095         // we decide to punish our counterparty for revoking their funds (as we don't currently
8096         // implement that).
8097         let chanmon_cfgs = create_chanmon_cfgs(2);
8098         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8099         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8100         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8101         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8102
8103         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8104         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8105
8106         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8107
8108         // Make signer believe we got a counterparty signature, so that it allows the revocation
8109         keys.get_enforcement_state().last_holder_commitment -= 1;
8110         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8111
8112         // Must revoke without gaps
8113         keys.get_enforcement_state().last_holder_commitment -= 1;
8114         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8115
8116         keys.get_enforcement_state().last_holder_commitment -= 1;
8117         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8118                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8119
8120         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8121                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8122         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8123         check_added_monitors!(nodes[1], 1);
8124         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8125 }
8126
8127 #[test]
8128 fn test_bump_txn_sanitize_tracking_maps() {
8129         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8130         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8131
8132         let chanmon_cfgs = create_chanmon_cfgs(2);
8133         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8134         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8135         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8136
8137         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8138         // Lock HTLC in both directions
8139         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8140         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8141
8142         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8143         assert_eq!(revoked_local_txn[0].input.len(), 1);
8144         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8145
8146         // Revoke local commitment tx
8147         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8148
8149         // Broadcast set of revoked txn on A
8150         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8151         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8152         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8153
8154         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8155         check_closed_broadcast!(nodes[0], true);
8156         check_added_monitors!(nodes[0], 1);
8157         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8158         let penalty_txn = {
8159                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8160                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8161                 check_spends!(node_txn[0], revoked_local_txn[0]);
8162                 check_spends!(node_txn[1], revoked_local_txn[0]);
8163                 check_spends!(node_txn[2], revoked_local_txn[0]);
8164                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8165                 node_txn.clear();
8166                 penalty_txn
8167         };
8168         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8169         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8170         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8171         {
8172                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8173                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8174                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8175         }
8176 }
8177
8178 #[test]
8179 fn test_pending_claimed_htlc_no_balance_underflow() {
8180         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8181         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8182         let chanmon_cfgs = create_chanmon_cfgs(2);
8183         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8184         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8185         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8186         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8187
8188         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8189         nodes[1].node.claim_funds(payment_preimage);
8190         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8191         check_added_monitors!(nodes[1], 1);
8192         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8193
8194         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8195         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8196         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8197         check_added_monitors!(nodes[0], 1);
8198         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8199
8200         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8201         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8202         // can get our balance.
8203
8204         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8205         // the public key of the only hop. This works around ChannelDetails not showing the
8206         // almost-claimed HTLC as available balance.
8207         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8208         route.payment_params = None; // This is all wrong, but unnecessary
8209         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8210         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8211         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8212
8213         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8214 }
8215
8216 #[test]
8217 fn test_channel_conf_timeout() {
8218         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8219         // confirm within 2016 blocks, as recommended by BOLT 2.
8220         let chanmon_cfgs = create_chanmon_cfgs(2);
8221         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8222         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8223         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8224
8225         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8226
8227         // The outbound node should wait forever for confirmation:
8228         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8229         // copied here instead of directly referencing the constant.
8230         connect_blocks(&nodes[0], 2016);
8231         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8232
8233         // The inbound node should fail the channel after exactly 2016 blocks
8234         connect_blocks(&nodes[1], 2015);
8235         check_added_monitors!(nodes[1], 0);
8236         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8237
8238         connect_blocks(&nodes[1], 1);
8239         check_added_monitors!(nodes[1], 1);
8240         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8241         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8242         assert_eq!(close_ev.len(), 1);
8243         match close_ev[0] {
8244                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8245                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8246                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8247                 },
8248                 _ => panic!("Unexpected event"),
8249         }
8250 }
8251
8252 #[test]
8253 fn test_override_channel_config() {
8254         let chanmon_cfgs = create_chanmon_cfgs(2);
8255         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8256         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8257         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8258
8259         // Node0 initiates a channel to node1 using the override config.
8260         let mut override_config = UserConfig::default();
8261         override_config.channel_handshake_config.our_to_self_delay = 200;
8262
8263         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8264
8265         // Assert the channel created by node0 is using the override config.
8266         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8267         assert_eq!(res.channel_flags, 0);
8268         assert_eq!(res.to_self_delay, 200);
8269 }
8270
8271 #[test]
8272 fn test_override_0msat_htlc_minimum() {
8273         let mut zero_config = UserConfig::default();
8274         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8275         let chanmon_cfgs = create_chanmon_cfgs(2);
8276         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8277         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8278         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8279
8280         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8281         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8282         assert_eq!(res.htlc_minimum_msat, 1);
8283
8284         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8285         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8286         assert_eq!(res.htlc_minimum_msat, 1);
8287 }
8288
8289 #[test]
8290 fn test_channel_update_has_correct_htlc_maximum_msat() {
8291         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8292         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8293         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8294         // 90% of the `channel_value`.
8295         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8296
8297         let mut config_30_percent = UserConfig::default();
8298         config_30_percent.channel_handshake_config.announced_channel = true;
8299         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8300         let mut config_50_percent = UserConfig::default();
8301         config_50_percent.channel_handshake_config.announced_channel = true;
8302         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8303         let mut config_95_percent = UserConfig::default();
8304         config_95_percent.channel_handshake_config.announced_channel = true;
8305         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8306         let mut config_100_percent = UserConfig::default();
8307         config_100_percent.channel_handshake_config.announced_channel = true;
8308         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8309
8310         let chanmon_cfgs = create_chanmon_cfgs(4);
8311         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8312         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)]);
8313         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8314
8315         let channel_value_satoshis = 100000;
8316         let channel_value_msat = channel_value_satoshis * 1000;
8317         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8318         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8319         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8320
8321         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());
8322         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());
8323
8324         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8325         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8326         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8327         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8328         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8329         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8330
8331         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8332         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8333         // `channel_value`.
8334         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8335         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8336         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8337         // `channel_value`.
8338         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8339 }
8340
8341 #[test]
8342 fn test_manually_accept_inbound_channel_request() {
8343         let mut manually_accept_conf = UserConfig::default();
8344         manually_accept_conf.manually_accept_inbound_channels = true;
8345         let chanmon_cfgs = create_chanmon_cfgs(2);
8346         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8347         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8348         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8349
8350         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8351         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8352
8353         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8354
8355         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8356         // accepting the inbound channel request.
8357         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8358
8359         let events = nodes[1].node.get_and_clear_pending_events();
8360         match events[0] {
8361                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8362                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8363                 }
8364                 _ => panic!("Unexpected event"),
8365         }
8366
8367         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8368         assert_eq!(accept_msg_ev.len(), 1);
8369
8370         match accept_msg_ev[0] {
8371                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8372                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8373                 }
8374                 _ => panic!("Unexpected event"),
8375         }
8376
8377         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8378
8379         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8380         assert_eq!(close_msg_ev.len(), 1);
8381
8382         let events = nodes[1].node.get_and_clear_pending_events();
8383         match events[0] {
8384                 Event::ChannelClosed { user_channel_id, .. } => {
8385                         assert_eq!(user_channel_id, 23);
8386                 }
8387                 _ => panic!("Unexpected event"),
8388         }
8389 }
8390
8391 #[test]
8392 fn test_manually_reject_inbound_channel_request() {
8393         let mut manually_accept_conf = UserConfig::default();
8394         manually_accept_conf.manually_accept_inbound_channels = true;
8395         let chanmon_cfgs = create_chanmon_cfgs(2);
8396         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8397         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8398         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8399
8400         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8401         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8402
8403         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8404
8405         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8406         // rejecting the inbound channel request.
8407         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8408
8409         let events = nodes[1].node.get_and_clear_pending_events();
8410         match events[0] {
8411                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8412                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8413                 }
8414                 _ => panic!("Unexpected event"),
8415         }
8416
8417         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8418         assert_eq!(close_msg_ev.len(), 1);
8419
8420         match close_msg_ev[0] {
8421                 MessageSendEvent::HandleError { ref node_id, .. } => {
8422                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8423                 }
8424                 _ => panic!("Unexpected event"),
8425         }
8426         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8427 }
8428
8429 #[test]
8430 fn test_reject_funding_before_inbound_channel_accepted() {
8431         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8432         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8433         // the node operator before the counterparty sends a `FundingCreated` message. If a
8434         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8435         // and the channel should be closed.
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         let temp_channel_id = res.temporary_channel_id;
8446
8447         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8448
8449         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8450         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8451
8452         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8453         nodes[1].node.get_and_clear_pending_events();
8454
8455         // Get the `AcceptChannel` message of `nodes[1]` without calling
8456         // `ChannelManager::accept_inbound_channel`, which generates a
8457         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8458         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8459         // succeed when `nodes[0]` is passed to it.
8460         {
8461                 let mut lock;
8462                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8463                 let accept_chan_msg = channel.get_accept_channel_message();
8464                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8465         }
8466
8467         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8468
8469         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8470         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8471
8472         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8473         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8474
8475         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8476         assert_eq!(close_msg_ev.len(), 1);
8477
8478         let expected_err = "FundingCreated message received before the channel was accepted";
8479         match close_msg_ev[0] {
8480                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8481                         assert_eq!(msg.channel_id, temp_channel_id);
8482                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8483                         assert_eq!(msg.data, expected_err);
8484                 }
8485                 _ => panic!("Unexpected event"),
8486         }
8487
8488         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8489 }
8490
8491 #[test]
8492 fn test_can_not_accept_inbound_channel_twice() {
8493         let mut manually_accept_conf = UserConfig::default();
8494         manually_accept_conf.manually_accept_inbound_channels = true;
8495         let chanmon_cfgs = create_chanmon_cfgs(2);
8496         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8497         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8498         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8499
8500         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8501         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8502
8503         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8504
8505         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8506         // accepting the inbound channel request.
8507         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8508
8509         let events = nodes[1].node.get_and_clear_pending_events();
8510         match events[0] {
8511                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8512                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8513                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8514                         match api_res {
8515                                 Err(APIError::APIMisuseError { err }) => {
8516                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8517                                 },
8518                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8519                                 Err(_) => panic!("Unexpected Error"),
8520                         }
8521                 }
8522                 _ => panic!("Unexpected event"),
8523         }
8524
8525         // Ensure that the channel wasn't closed after attempting to accept it twice.
8526         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8527         assert_eq!(accept_msg_ev.len(), 1);
8528
8529         match accept_msg_ev[0] {
8530                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8531                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8532                 }
8533                 _ => panic!("Unexpected event"),
8534         }
8535 }
8536
8537 #[test]
8538 fn test_can_not_accept_unknown_inbound_channel() {
8539         let chanmon_cfg = create_chanmon_cfgs(2);
8540         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8541         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8542         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8543
8544         let unknown_channel_id = [0; 32];
8545         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8546         match api_res {
8547                 Err(APIError::ChannelUnavailable { err }) => {
8548                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8549                 },
8550                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8551                 Err(_) => panic!("Unexpected Error"),
8552         }
8553 }
8554
8555 #[test]
8556 fn test_simple_mpp() {
8557         // Simple test of sending a multi-path payment.
8558         let chanmon_cfgs = create_chanmon_cfgs(4);
8559         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8560         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8561         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8562
8563         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8564         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8565         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8566         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8567
8568         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8569         let path = route.paths[0].clone();
8570         route.paths.push(path);
8571         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8572         route.paths[0][0].short_channel_id = chan_1_id;
8573         route.paths[0][1].short_channel_id = chan_3_id;
8574         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8575         route.paths[1][0].short_channel_id = chan_2_id;
8576         route.paths[1][1].short_channel_id = chan_4_id;
8577         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8578         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8579 }
8580
8581 #[test]
8582 fn test_preimage_storage() {
8583         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8584         let chanmon_cfgs = create_chanmon_cfgs(2);
8585         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8586         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8587         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8588
8589         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8590
8591         {
8592                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8593                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8594                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8595                 check_added_monitors!(nodes[0], 1);
8596                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8597                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8598                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8599                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8600         }
8601         // Note that after leaving the above scope we have no knowledge of any arguments or return
8602         // values from previous calls.
8603         expect_pending_htlcs_forwardable!(nodes[1]);
8604         let events = nodes[1].node.get_and_clear_pending_events();
8605         assert_eq!(events.len(), 1);
8606         match events[0] {
8607                 Event::PaymentReceived { ref purpose, .. } => {
8608                         match &purpose {
8609                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8610                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8611                                 },
8612                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8613                         }
8614                 },
8615                 _ => panic!("Unexpected event"),
8616         }
8617 }
8618
8619 #[test]
8620 #[allow(deprecated)]
8621 fn test_secret_timeout() {
8622         // Simple test of payment secret storage time outs. After
8623         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8624         let chanmon_cfgs = create_chanmon_cfgs(2);
8625         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8626         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8627         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8628
8629         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8630
8631         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8632
8633         // We should fail to register the same payment hash twice, at least until we've connected a
8634         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8635         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8636                 assert_eq!(err, "Duplicate payment hash");
8637         } else { panic!(); }
8638         let mut block = {
8639                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8640                 Block {
8641                         header: BlockHeader {
8642                                 version: 0x2000000,
8643                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8644                                 merkle_root: Default::default(),
8645                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8646                         txdata: vec![],
8647                 }
8648         };
8649         connect_block(&nodes[1], &block);
8650         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8651                 assert_eq!(err, "Duplicate payment hash");
8652         } else { panic!(); }
8653
8654         // If we then connect the second block, we should be able to register the same payment hash
8655         // again (this time getting a new payment secret).
8656         block.header.prev_blockhash = block.header.block_hash();
8657         block.header.time += 1;
8658         connect_block(&nodes[1], &block);
8659         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8660         assert_ne!(payment_secret_1, our_payment_secret);
8661
8662         {
8663                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8664                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8665                 check_added_monitors!(nodes[0], 1);
8666                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8667                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8668                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8669                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8670         }
8671         // Note that after leaving the above scope we have no knowledge of any arguments or return
8672         // values from previous calls.
8673         expect_pending_htlcs_forwardable!(nodes[1]);
8674         let events = nodes[1].node.get_and_clear_pending_events();
8675         assert_eq!(events.len(), 1);
8676         match events[0] {
8677                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8678                         assert!(payment_preimage.is_none());
8679                         assert_eq!(payment_secret, our_payment_secret);
8680                         // We don't actually have the payment preimage with which to claim this payment!
8681                 },
8682                 _ => panic!("Unexpected event"),
8683         }
8684 }
8685
8686 #[test]
8687 fn test_bad_secret_hash() {
8688         // Simple test of unregistered payment hash/invalid payment secret handling
8689         let chanmon_cfgs = create_chanmon_cfgs(2);
8690         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8691         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8692         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8693
8694         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8695
8696         let random_payment_hash = PaymentHash([42; 32]);
8697         let random_payment_secret = PaymentSecret([43; 32]);
8698         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8699         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8700
8701         // All the below cases should end up being handled exactly identically, so we macro the
8702         // resulting events.
8703         macro_rules! handle_unknown_invalid_payment_data {
8704                 () => {
8705                         check_added_monitors!(nodes[0], 1);
8706                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8707                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8708                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8709                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8710
8711                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8712                         // again to process the pending backwards-failure of the HTLC
8713                         expect_pending_htlcs_forwardable!(nodes[1]);
8714                         expect_pending_htlcs_forwardable!(nodes[1]);
8715                         check_added_monitors!(nodes[1], 1);
8716
8717                         // We should fail the payment back
8718                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8719                         match events.pop().unwrap() {
8720                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8721                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8722                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8723                                 },
8724                                 _ => panic!("Unexpected event"),
8725                         }
8726                 }
8727         }
8728
8729         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8730         // Error data is the HTLC value (100,000) and current block height
8731         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8732
8733         // Send a payment with the right payment hash but the wrong payment secret
8734         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8735         handle_unknown_invalid_payment_data!();
8736         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8737
8738         // Send a payment with a random payment hash, but the right payment secret
8739         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8740         handle_unknown_invalid_payment_data!();
8741         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8742
8743         // Send a payment with a random payment hash and random payment secret
8744         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8745         handle_unknown_invalid_payment_data!();
8746         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8747 }
8748
8749 #[test]
8750 fn test_update_err_monitor_lockdown() {
8751         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8752         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8753         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8754         //
8755         // This scenario may happen in a watchtower setup, where watchtower process a block height
8756         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8757         // commitment at same time.
8758
8759         let chanmon_cfgs = create_chanmon_cfgs(2);
8760         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8761         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8762         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8763
8764         // Create some initial channel
8765         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8766         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8767
8768         // Rebalance the network to generate htlc in the two directions
8769         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8770
8771         // Route a HTLC from node 0 to node 1 (but don't settle)
8772         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8773
8774         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8775         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8776         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8777         let persister = test_utils::TestPersister::new();
8778         let watchtower = {
8779                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8780                 let mut w = test_utils::TestVecWriter(Vec::new());
8781                 monitor.write(&mut w).unwrap();
8782                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8783                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8784                 assert!(new_monitor == *monitor);
8785                 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);
8786                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8787                 watchtower
8788         };
8789         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8790         let block = Block { header, txdata: vec![] };
8791         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8792         // transaction lock time requirements here.
8793         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8794         watchtower.chain_monitor.block_connected(&block, 200);
8795
8796         // Try to update ChannelMonitor
8797         nodes[1].node.claim_funds(preimage);
8798         check_added_monitors!(nodes[1], 1);
8799         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8800
8801         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8802         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8803         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8804         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8805                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8806                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8807                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8808                 } else { assert!(false); }
8809         } else { assert!(false); };
8810         // Our local monitor is in-sync and hasn't processed yet timeout
8811         check_added_monitors!(nodes[0], 1);
8812         let events = nodes[0].node.get_and_clear_pending_events();
8813         assert_eq!(events.len(), 1);
8814 }
8815
8816 #[test]
8817 fn test_concurrent_monitor_claim() {
8818         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8819         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8820         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8821         // state N+1 confirms. Alice claims output from state N+1.
8822
8823         let chanmon_cfgs = create_chanmon_cfgs(2);
8824         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8825         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8826         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8827
8828         // Create some initial channel
8829         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8830         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8831
8832         // Rebalance the network to generate htlc in the two directions
8833         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8834
8835         // Route a HTLC from node 0 to node 1 (but don't settle)
8836         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8837
8838         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8839         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8840         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8841         let persister = test_utils::TestPersister::new();
8842         let watchtower_alice = {
8843                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8844                 let mut w = test_utils::TestVecWriter(Vec::new());
8845                 monitor.write(&mut w).unwrap();
8846                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8847                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8848                 assert!(new_monitor == *monitor);
8849                 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);
8850                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8851                 watchtower
8852         };
8853         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8854         let block = Block { header, txdata: vec![] };
8855         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8856         // transaction lock time requirements here.
8857         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));
8858         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8859
8860         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8861         {
8862                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8863                 assert_eq!(txn.len(), 2);
8864                 txn.clear();
8865         }
8866
8867         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8868         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8869         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8870         let persister = test_utils::TestPersister::new();
8871         let watchtower_bob = {
8872                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8873                 let mut w = test_utils::TestVecWriter(Vec::new());
8874                 monitor.write(&mut w).unwrap();
8875                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8876                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8877                 assert!(new_monitor == *monitor);
8878                 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);
8879                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8880                 watchtower
8881         };
8882         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8883         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8884
8885         // Route another payment to generate another update with still previous HTLC pending
8886         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8887         {
8888                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8889         }
8890         check_added_monitors!(nodes[1], 1);
8891
8892         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8893         assert_eq!(updates.update_add_htlcs.len(), 1);
8894         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8895         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8896                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8897                         // Watchtower Alice should already have seen the block and reject the update
8898                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8899                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8900                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8901                 } else { assert!(false); }
8902         } else { assert!(false); };
8903         // Our local monitor is in-sync and hasn't processed yet timeout
8904         check_added_monitors!(nodes[0], 1);
8905
8906         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8907         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8908         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8909
8910         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8911         let bob_state_y;
8912         {
8913                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8914                 assert_eq!(txn.len(), 2);
8915                 bob_state_y = txn[0].clone();
8916                 txn.clear();
8917         };
8918
8919         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8920         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8921         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);
8922         {
8923                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8924                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8925                 // the onchain detection of the HTLC output
8926                 assert_eq!(htlc_txn.len(), 2);
8927                 check_spends!(htlc_txn[0], bob_state_y);
8928                 check_spends!(htlc_txn[1], bob_state_y);
8929         }
8930 }
8931
8932 #[test]
8933 fn test_pre_lockin_no_chan_closed_update() {
8934         // Test that if a peer closes a channel in response to a funding_created message we don't
8935         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8936         // message).
8937         //
8938         // Doing so would imply a channel monitor update before the initial channel monitor
8939         // registration, violating our API guarantees.
8940         //
8941         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8942         // then opening a second channel with the same funding output as the first (which is not
8943         // rejected because the first channel does not exist in the ChannelManager) and closing it
8944         // before receiving funding_signed.
8945         let chanmon_cfgs = create_chanmon_cfgs(2);
8946         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8947         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8948         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8949
8950         // Create an initial channel
8951         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8952         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8953         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8954         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8955         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8956
8957         // Move the first channel through the funding flow...
8958         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8959
8960         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8961         check_added_monitors!(nodes[0], 0);
8962
8963         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8964         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8965         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8966         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8967         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8968 }
8969
8970 #[test]
8971 fn test_htlc_no_detection() {
8972         // This test is a mutation to underscore the detection logic bug we had
8973         // before #653. HTLC value routed is above the remaining balance, thus
8974         // inverting HTLC and `to_remote` output. HTLC will come second and
8975         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8976         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8977         // outputs order detection for correct spending children filtring.
8978
8979         let chanmon_cfgs = create_chanmon_cfgs(2);
8980         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8981         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8982         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8983
8984         // Create some initial channels
8985         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8986
8987         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8988         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8989         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8990         assert_eq!(local_txn[0].input.len(), 1);
8991         assert_eq!(local_txn[0].output.len(), 3);
8992         check_spends!(local_txn[0], chan_1.3);
8993
8994         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8995         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8996         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8997         // We deliberately connect the local tx twice as this should provoke a failure calling
8998         // this test before #653 fix.
8999         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);
9000         check_closed_broadcast!(nodes[0], true);
9001         check_added_monitors!(nodes[0], 1);
9002         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
9003         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9004
9005         let htlc_timeout = {
9006                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9007                 assert_eq!(node_txn[1].input.len(), 1);
9008                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9009                 check_spends!(node_txn[1], local_txn[0]);
9010                 node_txn[1].clone()
9011         };
9012
9013         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9014         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9015         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9016         expect_payment_failed!(nodes[0], our_payment_hash, true);
9017 }
9018
9019 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9020         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9021         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9022         // Carol, Alice would be the upstream node, and Carol the downstream.)
9023         //
9024         // Steps of the test:
9025         // 1) Alice sends a HTLC to Carol through Bob.
9026         // 2) Carol doesn't settle the HTLC.
9027         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9028         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9029         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9030         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9031         // 5) Carol release the preimage to Bob off-chain.
9032         // 6) Bob claims the offered output on the broadcasted commitment.
9033         let chanmon_cfgs = create_chanmon_cfgs(3);
9034         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9035         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9036         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9037
9038         // Create some initial channels
9039         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9040         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9041
9042         // Steps (1) and (2):
9043         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9044         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9045
9046         // Check that Alice's commitment transaction now contains an output for this HTLC.
9047         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9048         check_spends!(alice_txn[0], chan_ab.3);
9049         assert_eq!(alice_txn[0].output.len(), 2);
9050         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9051         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9052         assert_eq!(alice_txn.len(), 2);
9053
9054         // Steps (3) and (4):
9055         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9056         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9057         let mut force_closing_node = 0; // Alice force-closes
9058         let mut counterparty_node = 1; // Bob if Alice force-closes
9059
9060         // Bob force-closes
9061         if !broadcast_alice {
9062                 force_closing_node = 1;
9063                 counterparty_node = 0;
9064         }
9065         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9066         check_closed_broadcast!(nodes[force_closing_node], true);
9067         check_added_monitors!(nodes[force_closing_node], 1);
9068         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9069         if go_onchain_before_fulfill {
9070                 let txn_to_broadcast = match broadcast_alice {
9071                         true => alice_txn.clone(),
9072                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9073                 };
9074                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9075                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9076                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9077                 if broadcast_alice {
9078                         check_closed_broadcast!(nodes[1], true);
9079                         check_added_monitors!(nodes[1], 1);
9080                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9081                 }
9082                 assert_eq!(bob_txn.len(), 1);
9083                 check_spends!(bob_txn[0], chan_ab.3);
9084         }
9085
9086         // Step (5):
9087         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9088         // process of removing the HTLC from their commitment transactions.
9089         nodes[2].node.claim_funds(payment_preimage);
9090         check_added_monitors!(nodes[2], 1);
9091         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9092
9093         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9094         assert!(carol_updates.update_add_htlcs.is_empty());
9095         assert!(carol_updates.update_fail_htlcs.is_empty());
9096         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9097         assert!(carol_updates.update_fee.is_none());
9098         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9099
9100         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9101         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9102         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9103         if !go_onchain_before_fulfill && broadcast_alice {
9104                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9105                 assert_eq!(events.len(), 1);
9106                 match events[0] {
9107                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9108                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9109                         },
9110                         _ => panic!("Unexpected event"),
9111                 };
9112         }
9113         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9114         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9115         // Carol<->Bob's updated commitment transaction info.
9116         check_added_monitors!(nodes[1], 2);
9117
9118         let events = nodes[1].node.get_and_clear_pending_msg_events();
9119         assert_eq!(events.len(), 2);
9120         let bob_revocation = match events[0] {
9121                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9122                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9123                         (*msg).clone()
9124                 },
9125                 _ => panic!("Unexpected event"),
9126         };
9127         let bob_updates = match events[1] {
9128                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9129                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9130                         (*updates).clone()
9131                 },
9132                 _ => panic!("Unexpected event"),
9133         };
9134
9135         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9136         check_added_monitors!(nodes[2], 1);
9137         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9138         check_added_monitors!(nodes[2], 1);
9139
9140         let events = nodes[2].node.get_and_clear_pending_msg_events();
9141         assert_eq!(events.len(), 1);
9142         let carol_revocation = match events[0] {
9143                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9144                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9145                         (*msg).clone()
9146                 },
9147                 _ => panic!("Unexpected event"),
9148         };
9149         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9150         check_added_monitors!(nodes[1], 1);
9151
9152         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9153         // here's where we put said channel's commitment tx on-chain.
9154         let mut txn_to_broadcast = alice_txn.clone();
9155         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9156         if !go_onchain_before_fulfill {
9157                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9158                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9159                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9160                 if broadcast_alice {
9161                         check_closed_broadcast!(nodes[1], true);
9162                         check_added_monitors!(nodes[1], 1);
9163                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9164                 }
9165                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9166                 if broadcast_alice {
9167                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9168                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9169                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9170                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9171                         // broadcasted.
9172                         assert_eq!(bob_txn.len(), 3);
9173                         check_spends!(bob_txn[1], chan_ab.3);
9174                 } else {
9175                         assert_eq!(bob_txn.len(), 2);
9176                         check_spends!(bob_txn[0], chan_ab.3);
9177                 }
9178         }
9179
9180         // Step (6):
9181         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9182         // broadcasted commitment transaction.
9183         {
9184                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9185                 if go_onchain_before_fulfill {
9186                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9187                         assert_eq!(bob_txn.len(), 2);
9188                 }
9189                 let script_weight = match broadcast_alice {
9190                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9191                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9192                 };
9193                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9194                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9195                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9196                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9197                 if broadcast_alice && !go_onchain_before_fulfill {
9198                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9199                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9200                 } else {
9201                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9202                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9203                 }
9204         }
9205 }
9206
9207 #[test]
9208 fn test_onchain_htlc_settlement_after_close() {
9209         do_test_onchain_htlc_settlement_after_close(true, true);
9210         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9211         do_test_onchain_htlc_settlement_after_close(true, false);
9212         do_test_onchain_htlc_settlement_after_close(false, false);
9213 }
9214
9215 #[test]
9216 fn test_duplicate_chan_id() {
9217         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9218         // already open we reject it and keep the old channel.
9219         //
9220         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9221         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9222         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9223         // updating logic for the existing channel.
9224         let chanmon_cfgs = create_chanmon_cfgs(2);
9225         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9226         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9227         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9228
9229         // Create an initial channel
9230         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9231         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9232         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9233         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()));
9234
9235         // Try to create a second channel with the same temporary_channel_id as the first and check
9236         // that it is rejected.
9237         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9238         {
9239                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9240                 assert_eq!(events.len(), 1);
9241                 match events[0] {
9242                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9243                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9244                                 // first (valid) and second (invalid) channels are closed, given they both have
9245                                 // the same non-temporary channel_id. However, currently we do not, so we just
9246                                 // move forward with it.
9247                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9248                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9249                         },
9250                         _ => panic!("Unexpected event"),
9251                 }
9252         }
9253
9254         // Move the first channel through the funding flow...
9255         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9256
9257         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9258         check_added_monitors!(nodes[0], 0);
9259
9260         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9261         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9262         {
9263                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9264                 assert_eq!(added_monitors.len(), 1);
9265                 assert_eq!(added_monitors[0].0, funding_output);
9266                 added_monitors.clear();
9267         }
9268         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9269
9270         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9271         let channel_id = funding_outpoint.to_channel_id();
9272
9273         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9274         // temporary one).
9275
9276         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9277         // Technically this is allowed by the spec, but we don't support it and there's little reason
9278         // to. Still, it shouldn't cause any other issues.
9279         open_chan_msg.temporary_channel_id = channel_id;
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
9287                                 // channels are closed, but currently we do not, so we just move forward with it.
9288                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9289                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9290                         },
9291                         _ => panic!("Unexpected event"),
9292                 }
9293         }
9294
9295         // Now try to create a second channel which has a duplicate funding output.
9296         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9297         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9298         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9299         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()));
9300         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9301
9302         let funding_created = {
9303                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9304                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9305                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9306                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9307                 // channelmanager in a possibly nonsense state instead).
9308                 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9309                 let logger = test_utils::TestLogger::new();
9310                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9311         };
9312         check_added_monitors!(nodes[0], 0);
9313         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9314         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9315         // still needs to be cleared here.
9316         check_added_monitors!(nodes[1], 1);
9317
9318         // ...still, nodes[1] will reject the duplicate channel.
9319         {
9320                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9321                 assert_eq!(events.len(), 1);
9322                 match events[0] {
9323                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9324                                 // Technically, at this point, nodes[1] would be justified in thinking both
9325                                 // channels are closed, but currently we do not, so we just move forward with it.
9326                                 assert_eq!(msg.channel_id, channel_id);
9327                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9328                         },
9329                         _ => panic!("Unexpected event"),
9330                 }
9331         }
9332
9333         // finally, finish creating the original channel and send a payment over it to make sure
9334         // everything is functional.
9335         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9336         {
9337                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9338                 assert_eq!(added_monitors.len(), 1);
9339                 assert_eq!(added_monitors[0].0, funding_output);
9340                 added_monitors.clear();
9341         }
9342
9343         let events_4 = nodes[0].node.get_and_clear_pending_events();
9344         assert_eq!(events_4.len(), 0);
9345         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9346         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9347
9348         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9349         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9350         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9351         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9352 }
9353
9354 #[test]
9355 fn test_error_chans_closed() {
9356         // Test that we properly handle error messages, closing appropriate channels.
9357         //
9358         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9359         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9360         // we can test various edge cases around it to ensure we don't regress.
9361         let chanmon_cfgs = create_chanmon_cfgs(3);
9362         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9363         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9364         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9365
9366         // Create some initial channels
9367         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9368         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9369         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9370
9371         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9372         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9373         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9374
9375         // Closing a channel from a different peer has no effect
9376         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9377         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9378
9379         // Closing one channel doesn't impact others
9380         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9381         check_added_monitors!(nodes[0], 1);
9382         check_closed_broadcast!(nodes[0], false);
9383         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9384         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9385         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9386         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);
9387         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);
9388
9389         // A null channel ID should close all channels
9390         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9391         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9392         check_added_monitors!(nodes[0], 2);
9393         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9394         let events = nodes[0].node.get_and_clear_pending_msg_events();
9395         assert_eq!(events.len(), 2);
9396         match events[0] {
9397                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9398                         assert_eq!(msg.contents.flags & 2, 2);
9399                 },
9400                 _ => panic!("Unexpected event"),
9401         }
9402         match events[1] {
9403                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9404                         assert_eq!(msg.contents.flags & 2, 2);
9405                 },
9406                 _ => panic!("Unexpected event"),
9407         }
9408         // Note that at this point users of a standard PeerHandler will end up calling
9409         // peer_disconnected with no_connection_possible set to false, duplicating the
9410         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9411         // users with their own peer handling logic. We duplicate the call here, however.
9412         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9413         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9414
9415         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9416         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9417         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9418 }
9419
9420 #[test]
9421 fn test_invalid_funding_tx() {
9422         // Test that we properly handle invalid funding transactions sent to us from a peer.
9423         //
9424         // Previously, all other major lightning implementations had failed to properly sanitize
9425         // funding transactions from their counterparties, leading to a multi-implementation critical
9426         // security vulnerability (though we always sanitized properly, we've previously had
9427         // un-released crashes in the sanitization process).
9428         //
9429         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9430         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9431         // gave up on it. We test this here by generating such a transaction.
9432         let chanmon_cfgs = create_chanmon_cfgs(2);
9433         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9434         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9435         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9436
9437         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9438         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()));
9439         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()));
9440
9441         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9442
9443         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9444         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9445         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9446         // its length.
9447         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9448         assert!(chan_utils::HTLCType::scriptlen_to_htlctype(wit_program.len()).unwrap() ==
9449                 chan_utils::HTLCType::AcceptedHTLC);
9450
9451         let wit_program_script: Script = wit_program.clone().into();
9452         for output in tx.output.iter_mut() {
9453                 // Make the confirmed funding transaction have a bogus script_pubkey
9454                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9455         }
9456
9457         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9458         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()));
9459         check_added_monitors!(nodes[1], 1);
9460
9461         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()));
9462         check_added_monitors!(nodes[0], 1);
9463
9464         let events_1 = nodes[0].node.get_and_clear_pending_events();
9465         assert_eq!(events_1.len(), 0);
9466
9467         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9468         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9469         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9470
9471         let expected_err = "funding tx had wrong script/value or output index";
9472         confirm_transaction_at(&nodes[1], &tx, 1);
9473         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9474         check_added_monitors!(nodes[1], 1);
9475         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9476         assert_eq!(events_2.len(), 1);
9477         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9478                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9479                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9480                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9481                 } else { panic!(); }
9482         } else { panic!(); }
9483         assert_eq!(nodes[1].node.list_channels().len(), 0);
9484
9485         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9486         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9487         // as its not 32 bytes long.
9488         let mut spend_tx = Transaction {
9489                 version: 2i32, lock_time: 0,
9490                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9491                         previous_output: BitcoinOutPoint {
9492                                 txid: tx.txid(),
9493                                 vout: idx as u32,
9494                         },
9495                         script_sig: Script::new(),
9496                         sequence: 0xfffffffd,
9497                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9498                 }).collect(),
9499                 output: vec![TxOut {
9500                         value: 1000,
9501                         script_pubkey: Script::new(),
9502                 }]
9503         };
9504         check_spends!(spend_tx, tx);
9505         mine_transaction(&nodes[1], &spend_tx);
9506 }
9507
9508 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9509         // In the first version of the chain::Confirm interface, after a refactor was made to not
9510         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9511         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9512         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9513         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9514         // spending transaction until height N+1 (or greater). This was due to the way
9515         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9516         // spending transaction at the height the input transaction was confirmed at, not whether we
9517         // should broadcast a spending transaction at the current height.
9518         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9519         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9520         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9521         // until we learned about an additional block.
9522         //
9523         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9524         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9525         let chanmon_cfgs = create_chanmon_cfgs(3);
9526         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9527         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9528         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9529         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9530
9531         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9532         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9533         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9534         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9535         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9536
9537         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9538         check_closed_broadcast!(nodes[1], true);
9539         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9540         check_added_monitors!(nodes[1], 1);
9541         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9542         assert_eq!(node_txn.len(), 1);
9543
9544         let conf_height = nodes[1].best_block_info().1;
9545         if !test_height_before_timelock {
9546                 connect_blocks(&nodes[1], 24 * 6);
9547         }
9548         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9549                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9550         if test_height_before_timelock {
9551                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9552                 // generate any events or broadcast any transactions
9553                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9554                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9555         } else {
9556                 // We should broadcast an HTLC transaction spending our funding transaction first
9557                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9558                 assert_eq!(spending_txn.len(), 2);
9559                 assert_eq!(spending_txn[0], node_txn[0]);
9560                 check_spends!(spending_txn[1], node_txn[0]);
9561                 // We should also generate a SpendableOutputs event with the to_self output (as its
9562                 // timelock is up).
9563                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9564                 assert_eq!(descriptor_spend_txn.len(), 1);
9565
9566                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9567                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9568                 // additional block built on top of the current chain.
9569                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9570                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9571                 expect_pending_htlcs_forwardable!(nodes[1]);
9572                 check_added_monitors!(nodes[1], 1);
9573
9574                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9575                 assert!(updates.update_add_htlcs.is_empty());
9576                 assert!(updates.update_fulfill_htlcs.is_empty());
9577                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9578                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9579                 assert!(updates.update_fee.is_none());
9580                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9581                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9582                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9583         }
9584 }
9585
9586 #[test]
9587 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9588         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9589         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9590 }
9591
9592 #[test]
9593 fn test_forwardable_regen() {
9594         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9595         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9596         // HTLCs.
9597         // We test it for both payment receipt and payment forwarding.
9598
9599         let chanmon_cfgs = create_chanmon_cfgs(3);
9600         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9601         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9602         let persister: test_utils::TestPersister;
9603         let new_chain_monitor: test_utils::TestChainMonitor;
9604         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9605         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9606         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9607         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9608
9609         // First send a payment to nodes[1]
9610         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9611         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9612         check_added_monitors!(nodes[0], 1);
9613
9614         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9615         assert_eq!(events.len(), 1);
9616         let payment_event = SendEvent::from_event(events.pop().unwrap());
9617         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9618         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9619
9620         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9621
9622         // Next send a payment which is forwarded by nodes[1]
9623         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9624         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9625         check_added_monitors!(nodes[0], 1);
9626
9627         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9628         assert_eq!(events.len(), 1);
9629         let payment_event = SendEvent::from_event(events.pop().unwrap());
9630         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9631         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9632
9633         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9634         // generated
9635         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9636
9637         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9638         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9639         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9640
9641         let nodes_1_serialized = nodes[1].node.encode();
9642         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9643         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9644         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9645         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9646
9647         persister = test_utils::TestPersister::new();
9648         let keys_manager = &chanmon_cfgs[1].keys_manager;
9649         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);
9650         nodes[1].chain_monitor = &new_chain_monitor;
9651
9652         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9653         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9654                 &mut chan_0_monitor_read, keys_manager).unwrap();
9655         assert!(chan_0_monitor_read.is_empty());
9656         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9657         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9658                 &mut chan_1_monitor_read, keys_manager).unwrap();
9659         assert!(chan_1_monitor_read.is_empty());
9660
9661         let mut nodes_1_read = &nodes_1_serialized[..];
9662         let (_, nodes_1_deserialized_tmp) = {
9663                 let mut channel_monitors = HashMap::new();
9664                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9665                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9666                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9667                         default_config: UserConfig::default(),
9668                         keys_manager,
9669                         fee_estimator: node_cfgs[1].fee_estimator,
9670                         chain_monitor: nodes[1].chain_monitor,
9671                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9672                         logger: nodes[1].logger,
9673                         channel_monitors,
9674                 }).unwrap()
9675         };
9676         nodes_1_deserialized = nodes_1_deserialized_tmp;
9677         assert!(nodes_1_read.is_empty());
9678
9679         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9680         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9681         nodes[1].node = &nodes_1_deserialized;
9682         check_added_monitors!(nodes[1], 2);
9683
9684         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9685         // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9686         // the commitment state.
9687         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9688
9689         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9690
9691         expect_pending_htlcs_forwardable!(nodes[1]);
9692         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9693         check_added_monitors!(nodes[1], 1);
9694
9695         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9696         assert_eq!(events.len(), 1);
9697         let payment_event = SendEvent::from_event(events.pop().unwrap());
9698         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9699         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9700         expect_pending_htlcs_forwardable!(nodes[2]);
9701         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9702
9703         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9704         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9705 }
9706
9707 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9708         let chanmon_cfgs = create_chanmon_cfgs(2);
9709         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9710         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9711         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9712
9713         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9714
9715         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9716                 .with_features(InvoiceFeatures::known());
9717         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9718
9719         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9720
9721         {
9722                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9723                 check_added_monitors!(nodes[0], 1);
9724                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9725                 assert_eq!(events.len(), 1);
9726                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9727                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9728                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9729         }
9730         expect_pending_htlcs_forwardable!(nodes[1]);
9731         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9732
9733         {
9734                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9735                 check_added_monitors!(nodes[0], 1);
9736                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9737                 assert_eq!(events.len(), 1);
9738                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9739                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9740                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9741                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9742                 // assume the second is a privacy attack (no longer particularly relevant
9743                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9744                 // the first HTLC delivered above.
9745         }
9746
9747         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9748         nodes[1].node.process_pending_htlc_forwards();
9749
9750         if test_for_second_fail_panic {
9751                 // Now we go fail back the first HTLC from the user end.
9752                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9753
9754                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9755                 nodes[1].node.process_pending_htlc_forwards();
9756
9757                 check_added_monitors!(nodes[1], 1);
9758                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9759                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9760
9761                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9762                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9763                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9764
9765                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9766                 assert_eq!(failure_events.len(), 2);
9767                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9768                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9769         } else {
9770                 // Let the second HTLC fail and claim the first
9771                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9772                 nodes[1].node.process_pending_htlc_forwards();
9773
9774                 check_added_monitors!(nodes[1], 1);
9775                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9776                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9777                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9778
9779                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9780
9781                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9782         }
9783 }
9784
9785 #[test]
9786 fn test_dup_htlc_second_fail_panic() {
9787         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9788         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9789         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9790         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9791         do_test_dup_htlc_second_rejected(true);
9792 }
9793
9794 #[test]
9795 fn test_dup_htlc_second_rejected() {
9796         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9797         // simply reject the second HTLC but are still able to claim the first HTLC.
9798         do_test_dup_htlc_second_rejected(false);
9799 }
9800
9801 #[test]
9802 fn test_inconsistent_mpp_params() {
9803         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9804         // such HTLC and allow the second to stay.
9805         let chanmon_cfgs = create_chanmon_cfgs(4);
9806         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9807         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9808         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9809
9810         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9811         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9812         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9813         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9814
9815         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9816                 .with_features(InvoiceFeatures::known());
9817         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9818         assert_eq!(route.paths.len(), 2);
9819         route.paths.sort_by(|path_a, _| {
9820                 // Sort the path so that the path through nodes[1] comes first
9821                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9822                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9823         });
9824         let payment_params_opt = Some(payment_params);
9825
9826         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9827
9828         let cur_height = nodes[0].best_block_info().1;
9829         let payment_id = PaymentId([42; 32]);
9830         {
9831                 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();
9832                 check_added_monitors!(nodes[0], 1);
9833
9834                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9835                 assert_eq!(events.len(), 1);
9836                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9837         }
9838         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9839
9840         {
9841                 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();
9842                 check_added_monitors!(nodes[0], 1);
9843
9844                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9845                 assert_eq!(events.len(), 1);
9846                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9847
9848                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9849                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9850
9851                 expect_pending_htlcs_forwardable!(nodes[2]);
9852                 check_added_monitors!(nodes[2], 1);
9853
9854                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9855                 assert_eq!(events.len(), 1);
9856                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9857
9858                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9859                 check_added_monitors!(nodes[3], 0);
9860                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9861
9862                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9863                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9864                 // post-payment_secrets) and fail back the new HTLC.
9865         }
9866         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9867         nodes[3].node.process_pending_htlc_forwards();
9868         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9869         nodes[3].node.process_pending_htlc_forwards();
9870
9871         check_added_monitors!(nodes[3], 1);
9872
9873         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9874         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9875         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9876
9877         expect_pending_htlcs_forwardable!(nodes[2]);
9878         check_added_monitors!(nodes[2], 1);
9879
9880         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9881         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9882         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9883
9884         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9885
9886         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();
9887         check_added_monitors!(nodes[0], 1);
9888
9889         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9890         assert_eq!(events.len(), 1);
9891         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9892
9893         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9894 }
9895
9896 #[test]
9897 fn test_keysend_payments_to_public_node() {
9898         let chanmon_cfgs = create_chanmon_cfgs(2);
9899         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9900         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9901         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9902
9903         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9904         let network_graph = nodes[0].network_graph;
9905         let payer_pubkey = nodes[0].node.get_our_node_id();
9906         let payee_pubkey = nodes[1].node.get_our_node_id();
9907         let route_params = RouteParameters {
9908                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9909                 final_value_msat: 10000,
9910                 final_cltv_expiry_delta: 40,
9911         };
9912         let scorer = test_utils::TestScorer::with_penalty(0);
9913         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9914         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9915
9916         let test_preimage = PaymentPreimage([42; 32]);
9917         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9918         check_added_monitors!(nodes[0], 1);
9919         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9920         assert_eq!(events.len(), 1);
9921         let event = events.pop().unwrap();
9922         let path = vec![&nodes[1]];
9923         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9924         claim_payment(&nodes[0], &path, test_preimage);
9925 }
9926
9927 #[test]
9928 fn test_keysend_payments_to_private_node() {
9929         let chanmon_cfgs = create_chanmon_cfgs(2);
9930         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9931         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9932         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9933
9934         let payer_pubkey = nodes[0].node.get_our_node_id();
9935         let payee_pubkey = nodes[1].node.get_our_node_id();
9936         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9937         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9938
9939         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9940         let route_params = RouteParameters {
9941                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9942                 final_value_msat: 10000,
9943                 final_cltv_expiry_delta: 40,
9944         };
9945         let network_graph = nodes[0].network_graph;
9946         let first_hops = nodes[0].node.list_usable_channels();
9947         let scorer = test_utils::TestScorer::with_penalty(0);
9948         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9949         let route = find_route(
9950                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9951                 nodes[0].logger, &scorer, &random_seed_bytes
9952         ).unwrap();
9953
9954         let test_preimage = PaymentPreimage([42; 32]);
9955         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9956         check_added_monitors!(nodes[0], 1);
9957         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9958         assert_eq!(events.len(), 1);
9959         let event = events.pop().unwrap();
9960         let path = vec![&nodes[1]];
9961         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9962         claim_payment(&nodes[0], &path, test_preimage);
9963 }
9964
9965 #[test]
9966 fn test_double_partial_claim() {
9967         // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9968         // time out, the sender resends only some of the MPP parts, then the user processes the
9969         // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9970         // amount.
9971         let chanmon_cfgs = create_chanmon_cfgs(4);
9972         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9973         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9974         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9975
9976         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9977         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9978         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9979         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9980
9981         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9982         assert_eq!(route.paths.len(), 2);
9983         route.paths.sort_by(|path_a, _| {
9984                 // Sort the path so that the path through nodes[1] comes first
9985                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9986                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9987         });
9988
9989         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9990         // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
9991         // amount of time to respond to.
9992
9993         // Connect some blocks to time out the payment
9994         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9995         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9996
9997         expect_pending_htlcs_forwardable!(nodes[3]);
9998
9999         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
10000
10001         // nodes[1] now retries one of the two paths...
10002         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10003         check_added_monitors!(nodes[0], 2);
10004
10005         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10006         assert_eq!(events.len(), 2);
10007         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10008
10009         // At this point nodes[3] has received one half of the payment, and the user goes to handle
10010         // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
10011         nodes[3].node.claim_funds(payment_preimage);
10012         check_added_monitors!(nodes[3], 0);
10013         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
10014 }
10015
10016 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10017         // Test what happens if a node receives an MPP payment, claims it, but crashes before
10018         // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10019         // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10020         // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10021         // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10022         // not have the preimage tied to the still-pending HTLC.
10023         //
10024         // To get to the correct state, on startup we should propagate the preimage to the
10025         // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10026         // receiving the preimage without a state update.
10027         //
10028         // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10029         // definitely claimed.
10030         let chanmon_cfgs = create_chanmon_cfgs(4);
10031         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10032         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10033
10034         let persister: test_utils::TestPersister;
10035         let new_chain_monitor: test_utils::TestChainMonitor;
10036         let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10037
10038         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10039
10040         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10041         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10042         let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10043         let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10044
10045         // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10046         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10047         assert_eq!(route.paths.len(), 2);
10048         route.paths.sort_by(|path_a, _| {
10049                 // Sort the path so that the path through nodes[1] comes first
10050                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10051                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10052         });
10053
10054         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10055         check_added_monitors!(nodes[0], 2);
10056
10057         // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10058         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10059         assert_eq!(send_events.len(), 2);
10060         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);
10061         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);
10062
10063         // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10064         // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10065         let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10066         if !persist_both_monitors {
10067                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10068                         if outpoint.to_channel_id() == chan_id_not_persisted {
10069                                 assert!(original_monitor.0.is_empty());
10070                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10071                         }
10072                 }
10073         }
10074
10075         let mut original_manager = test_utils::TestVecWriter(Vec::new());
10076         nodes[3].node.write(&mut original_manager).unwrap();
10077
10078         expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10079
10080         nodes[3].node.claim_funds(payment_preimage);
10081         check_added_monitors!(nodes[3], 2);
10082         expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10083
10084         // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10085         // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10086         // with the old ChannelManager.
10087         let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10088         for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10089                 if outpoint.to_channel_id() == chan_id_persisted {
10090                         assert!(updated_monitor.0.is_empty());
10091                         nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10092                 }
10093         }
10094         // If `persist_both_monitors` is set, get the second monitor here as well
10095         if persist_both_monitors {
10096                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10097                         if outpoint.to_channel_id() == chan_id_not_persisted {
10098                                 assert!(original_monitor.0.is_empty());
10099                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10100                         }
10101                 }
10102         }
10103
10104         // Now restart nodes[3].
10105         persister = test_utils::TestPersister::new();
10106         let keys_manager = &chanmon_cfgs[3].keys_manager;
10107         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);
10108         nodes[3].chain_monitor = &new_chain_monitor;
10109         let mut monitors = Vec::new();
10110         for mut monitor_data in [original_monitor, updated_monitor].iter() {
10111                 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10112                 monitors.push(deserialized_monitor);
10113         }
10114
10115         let config = UserConfig::default();
10116         nodes_3_deserialized = {
10117                 let mut channel_monitors = HashMap::new();
10118                 for monitor in monitors.iter_mut() {
10119                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10120                 }
10121                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10122                         default_config: config,
10123                         keys_manager,
10124                         fee_estimator: node_cfgs[3].fee_estimator,
10125                         chain_monitor: nodes[3].chain_monitor,
10126                         tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10127                         logger: nodes[3].logger,
10128                         channel_monitors,
10129                 }).unwrap().1
10130         };
10131         nodes[3].node = &nodes_3_deserialized;
10132
10133         for monitor in monitors {
10134                 // On startup the preimage should have been copied into the non-persisted monitor:
10135                 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10136                 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10137         }
10138         check_added_monitors!(nodes[3], 2);
10139
10140         nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10141         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10142
10143         // During deserialization, we should have closed one channel and broadcast its latest
10144         // commitment transaction. We should also still have the original PaymentReceived event we
10145         // never finished processing.
10146         let events = nodes[3].node.get_and_clear_pending_events();
10147         assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10148         if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10149         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10150         if persist_both_monitors {
10151                 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10152         }
10153
10154         // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10155         // ChannelManager prior to handling the original one.
10156         if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10157                 events[if persist_both_monitors { 3 } else { 2 }]
10158         {
10159                 assert_eq!(payment_hash, our_payment_hash);
10160         } else { panic!(); }
10161
10162         assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10163         if !persist_both_monitors {
10164                 // If one of the two channels is still live, reveal the payment preimage over it.
10165
10166                 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10167                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10168                 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10169                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10170
10171                 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10172                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10173                 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10174
10175                 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10176
10177                 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10178                 // claim should fly.
10179                 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10180                 check_added_monitors!(nodes[3], 1);
10181                 assert_eq!(ds_msgs.len(), 2);
10182                 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10183
10184                 let cs_updates = match ds_msgs[0] {
10185                         MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10186                                 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10187                                 check_added_monitors!(nodes[2], 1);
10188                                 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10189                                 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10190                                 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10191                                 cs_updates
10192                         }
10193                         _ => panic!(),
10194                 };
10195
10196                 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10197                 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10198                 expect_payment_sent!(nodes[0], payment_preimage);
10199         }
10200 }
10201
10202 #[test]
10203 fn test_partial_claim_before_restart() {
10204         do_test_partial_claim_before_restart(false);
10205         do_test_partial_claim_before_restart(true);
10206 }
10207
10208 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10209 #[derive(Clone, Copy, PartialEq)]
10210 enum ExposureEvent {
10211         /// Breach occurs at HTLC forwarding (see `send_htlc`)
10212         AtHTLCForward,
10213         /// Breach occurs at HTLC reception (see `update_add_htlc`)
10214         AtHTLCReception,
10215         /// Breach occurs at outbound update_fee (see `send_update_fee`)
10216         AtUpdateFeeOutbound,
10217 }
10218
10219 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10220         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10221         // policy.
10222         //
10223         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10224         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10225         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10226         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10227         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10228         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10229         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10230         // might be available again for HTLC processing once the dust bandwidth has cleared up.
10231
10232         let chanmon_cfgs = create_chanmon_cfgs(2);
10233         let mut config = test_default_channel_config();
10234         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10235         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10236         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10237         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10238
10239         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10240         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10241         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10242         open_channel.max_accepted_htlcs = 60;
10243         if on_holder_tx {
10244                 open_channel.dust_limit_satoshis = 546;
10245         }
10246         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10247         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10248         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10249
10250         let opt_anchors = false;
10251
10252         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10253
10254         if on_holder_tx {
10255                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10256                         chan.holder_dust_limit_satoshis = 546;
10257                 }
10258         }
10259
10260         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10261         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()));
10262         check_added_monitors!(nodes[1], 1);
10263
10264         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()));
10265         check_added_monitors!(nodes[0], 1);
10266
10267         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10268         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10269         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10270
10271         let dust_buffer_feerate = {
10272                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10273                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10274                 chan.get_dust_buffer_feerate(None) as u64
10275         };
10276         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;
10277         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10278
10279         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;
10280         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10281
10282         let dust_htlc_on_counterparty_tx: u64 = 25;
10283         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10284
10285         if on_holder_tx {
10286                 if dust_outbound_balance {
10287                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10288                         // Outbound dust balance: 4372 sats
10289                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10290                         for i in 0..dust_outbound_htlc_on_holder_tx {
10291                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10292                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10293                         }
10294                 } else {
10295                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10296                         // Inbound dust balance: 4372 sats
10297                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10298                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10299                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10300                         }
10301                 }
10302         } else {
10303                 if dust_outbound_balance {
10304                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10305                         // Outbound dust balance: 5000 sats
10306                         for i in 0..dust_htlc_on_counterparty_tx {
10307                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10308                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10309                         }
10310                 } else {
10311                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10312                         // Inbound dust balance: 5000 sats
10313                         for _ in 0..dust_htlc_on_counterparty_tx {
10314                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10315                         }
10316                 }
10317         }
10318
10319         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10320         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10321                 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 });
10322                 let mut config = UserConfig::default();
10323                 // With default dust exposure: 5000 sats
10324                 if on_holder_tx {
10325                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10326                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10327                         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)));
10328                 } else {
10329                         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)));
10330                 }
10331         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10332                 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 });
10333                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10334                 check_added_monitors!(nodes[1], 1);
10335                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10336                 assert_eq!(events.len(), 1);
10337                 let payment_event = SendEvent::from_event(events.remove(0));
10338                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10339                 // With default dust exposure: 5000 sats
10340                 if on_holder_tx {
10341                         // Outbound dust balance: 6399 sats
10342                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10343                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10344                         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);
10345                 } else {
10346                         // Outbound dust balance: 5200 sats
10347                         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);
10348                 }
10349         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10350                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10351                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10352                 {
10353                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10354                         *feerate_lock = *feerate_lock * 10;
10355                 }
10356                 nodes[0].node.timer_tick_occurred();
10357                 check_added_monitors!(nodes[0], 1);
10358                 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);
10359         }
10360
10361         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10362         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10363         added_monitors.clear();
10364 }
10365
10366 #[test]
10367 fn test_max_dust_htlc_exposure() {
10368         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10369         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10370         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10371         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10372         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10373         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10374         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10375         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10376         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10377         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10378         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10379         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10380 }
10381
10382 #[test]
10383 fn test_non_final_funding_tx() {
10384         let chanmon_cfgs = create_chanmon_cfgs(2);
10385         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10386         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10387         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10388
10389         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10390         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10391         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
10392         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10393         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
10394
10395         let best_height = nodes[0].node.best_block.read().unwrap().height();
10396
10397         let chan_id = *nodes[0].network_chan_count.borrow();
10398         let events = nodes[0].node.get_and_clear_pending_events();
10399         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: 0x1, witness: Witness::from_vec(vec!(vec!(1))) };
10400         assert_eq!(events.len(), 1);
10401         let mut tx = match events[0] {
10402                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10403                         // Timelock the transaction _beyond_ the best client height + 2.
10404                         Transaction { version: chan_id as i32, lock_time: best_height + 3, input: vec![input], output: vec![TxOut {
10405                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10406                         }]}
10407                 },
10408                 _ => panic!("Unexpected event"),
10409         };
10410         // Transaction should fail as it's evaluated as non-final for propagation.
10411         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10412                 Err(APIError::APIMisuseError { err }) => {
10413                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10414                 },
10415                 _ => panic!()
10416         }
10417
10418         // However, transaction should be accepted if it's in a +2 headroom from best block.
10419         tx.lock_time -= 1;
10420         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10421         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10422 }