Reduce default max_channel_saturation_power_of_half to 2 (max 1/4)
[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         // Close down the channels...
1063         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1064         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1065         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1066         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1067         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1068         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1069         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1070         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1071         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1072         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1073         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1074         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1075 }
1076
1077 #[test]
1078 fn holding_cell_htlc_counting() {
1079         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1080         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1081         // commitment dance rounds.
1082         let chanmon_cfgs = create_chanmon_cfgs(3);
1083         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1084         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1085         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1086         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1087         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1088
1089         let mut payments = Vec::new();
1090         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1091                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1092                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1093                 payments.push((payment_preimage, payment_hash));
1094         }
1095         check_added_monitors!(nodes[1], 1);
1096
1097         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1098         assert_eq!(events.len(), 1);
1099         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1100         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1101
1102         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1103         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1104         // another HTLC.
1105         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1106         {
1107                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1108                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1109                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1110                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1111         }
1112
1113         // This should also be true if we try to forward a payment.
1114         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1115         {
1116                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1117                 check_added_monitors!(nodes[0], 1);
1118         }
1119
1120         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1121         assert_eq!(events.len(), 1);
1122         let payment_event = SendEvent::from_event(events.pop().unwrap());
1123         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1124
1125         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1126         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1127         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1128         // fails), the second will process the resulting failure and fail the HTLC backward.
1129         expect_pending_htlcs_forwardable!(nodes[1]);
1130         expect_pending_htlcs_forwardable!(nodes[1]);
1131         check_added_monitors!(nodes[1], 1);
1132
1133         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1134         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1135         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1136
1137         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1138
1139         // Now forward all the pending HTLCs and claim them back
1140         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1141         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1142         check_added_monitors!(nodes[2], 1);
1143
1144         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1145         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1146         check_added_monitors!(nodes[1], 1);
1147         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1148
1149         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1150         check_added_monitors!(nodes[1], 1);
1151         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1152
1153         for ref update in as_updates.update_add_htlcs.iter() {
1154                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1155         }
1156         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1157         check_added_monitors!(nodes[2], 1);
1158         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1159         check_added_monitors!(nodes[2], 1);
1160         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1161
1162         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1163         check_added_monitors!(nodes[1], 1);
1164         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1165         check_added_monitors!(nodes[1], 1);
1166         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1167
1168         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1169         check_added_monitors!(nodes[2], 1);
1170
1171         expect_pending_htlcs_forwardable!(nodes[2]);
1172
1173         let events = nodes[2].node.get_and_clear_pending_events();
1174         assert_eq!(events.len(), payments.len());
1175         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1176                 match event {
1177                         &Event::PaymentReceived { ref payment_hash, .. } => {
1178                                 assert_eq!(*payment_hash, *hash);
1179                         },
1180                         _ => panic!("Unexpected event"),
1181                 };
1182         }
1183
1184         for (preimage, _) in payments.drain(..) {
1185                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1186         }
1187
1188         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1189 }
1190
1191 #[test]
1192 fn duplicate_htlc_test() {
1193         // Test that we accept duplicate payment_hash HTLCs across the network and that
1194         // claiming/failing them are all separate and don't affect each other
1195         let chanmon_cfgs = create_chanmon_cfgs(6);
1196         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1197         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1198         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1199
1200         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1201         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1202         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1203         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1204         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1205         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1206
1207         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1208
1209         *nodes[0].network_payment_count.borrow_mut() -= 1;
1210         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1211
1212         *nodes[0].network_payment_count.borrow_mut() -= 1;
1213         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1214
1215         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1216         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1217         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1218 }
1219
1220 #[test]
1221 fn test_duplicate_htlc_different_direction_onchain() {
1222         // Test that ChannelMonitor doesn't generate 2 preimage txn
1223         // when we have 2 HTLCs with same preimage that go across a node
1224         // in opposite directions, even with the same payment secret.
1225         let chanmon_cfgs = create_chanmon_cfgs(2);
1226         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1227         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1228         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1229
1230         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1231
1232         // balancing
1233         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1234
1235         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1236
1237         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1238         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1239         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1240
1241         // Provide preimage to node 0 by claiming payment
1242         nodes[0].node.claim_funds(payment_preimage);
1243         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1244         check_added_monitors!(nodes[0], 1);
1245
1246         // Broadcast node 1 commitment txn
1247         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1248
1249         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1250         let mut has_both_htlcs = 0; // check htlcs match ones committed
1251         for outp in remote_txn[0].output.iter() {
1252                 if outp.value == 800_000 / 1000 {
1253                         has_both_htlcs += 1;
1254                 } else if outp.value == 900_000 / 1000 {
1255                         has_both_htlcs += 1;
1256                 }
1257         }
1258         assert_eq!(has_both_htlcs, 2);
1259
1260         mine_transaction(&nodes[0], &remote_txn[0]);
1261         check_added_monitors!(nodes[0], 1);
1262         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1263         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1264
1265         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1266         assert_eq!(claim_txn.len(), 8);
1267
1268         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1269
1270         check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1271         check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1272
1273         let bump_tx = if claim_txn[1] == claim_txn[4] {
1274                 assert_eq!(claim_txn[1], claim_txn[4]);
1275                 assert_eq!(claim_txn[2], claim_txn[5]);
1276
1277                 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1278
1279                 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1280                 &claim_txn[3]
1281         } else {
1282                 assert_eq!(claim_txn[1], claim_txn[3]);
1283                 assert_eq!(claim_txn[2], claim_txn[4]);
1284
1285                 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1286
1287                 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1288
1289                 &claim_txn[7]
1290         };
1291
1292         assert_eq!(claim_txn[0].input.len(), 1);
1293         assert_eq!(bump_tx.input.len(), 1);
1294         assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1295
1296         assert_eq!(claim_txn[0].input.len(), 1);
1297         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1298         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1299
1300         assert_eq!(claim_txn[6].input.len(), 1);
1301         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1302         check_spends!(claim_txn[6], remote_txn[0]);
1303         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1304
1305         let events = nodes[0].node.get_and_clear_pending_msg_events();
1306         assert_eq!(events.len(), 3);
1307         for e in events {
1308                 match e {
1309                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1310                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1311                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1312                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1313                         },
1314                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1315                                 assert!(update_add_htlcs.is_empty());
1316                                 assert!(update_fail_htlcs.is_empty());
1317                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1318                                 assert!(update_fail_malformed_htlcs.is_empty());
1319                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1320                         },
1321                         _ => panic!("Unexpected event"),
1322                 }
1323         }
1324 }
1325
1326 #[test]
1327 fn test_basic_channel_reserve() {
1328         let chanmon_cfgs = create_chanmon_cfgs(2);
1329         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1330         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1331         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1332         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1333
1334         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1335         let channel_reserve = chan_stat.channel_reserve_msat;
1336
1337         // The 2* and +1 are for the fee spike reserve.
1338         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1339         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1340         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1341         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1342         match err {
1343                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1344                         match &fails[0] {
1345                                 &APIError::ChannelUnavailable{ref err} =>
1346                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1347                                 _ => panic!("Unexpected error variant"),
1348                         }
1349                 },
1350                 _ => panic!("Unexpected error variant"),
1351         }
1352         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1353         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1354
1355         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1356 }
1357
1358 #[test]
1359 fn test_fee_spike_violation_fails_htlc() {
1360         let chanmon_cfgs = create_chanmon_cfgs(2);
1361         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1362         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1363         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1364         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1365
1366         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1367         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1368         let secp_ctx = Secp256k1::new();
1369         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1370
1371         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1372
1373         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1374         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1375         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1376         let msg = msgs::UpdateAddHTLC {
1377                 channel_id: chan.2,
1378                 htlc_id: 0,
1379                 amount_msat: htlc_msat,
1380                 payment_hash: payment_hash,
1381                 cltv_expiry: htlc_cltv,
1382                 onion_routing_packet: onion_packet,
1383         };
1384
1385         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1386
1387         // Now manually create the commitment_signed message corresponding to the update_add
1388         // nodes[0] just sent. In the code for construction of this message, "local" refers
1389         // to the sender of the message, and "remote" refers to the receiver.
1390
1391         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1392
1393         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1394
1395         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1396         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1397         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1398                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1399                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1400                 let chan_signer = local_chan.get_signer();
1401                 // Make the signer believe we validated another commitment, so we can release the secret
1402                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1403
1404                 let pubkeys = chan_signer.pubkeys();
1405                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1406                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1407                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1408                  chan_signer.pubkeys().funding_pubkey)
1409         };
1410         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1411                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1412                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1413                 let chan_signer = remote_chan.get_signer();
1414                 let pubkeys = chan_signer.pubkeys();
1415                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1416                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1417                  chan_signer.pubkeys().funding_pubkey)
1418         };
1419
1420         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1421         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1422                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1423
1424         // Build the remote commitment transaction so we can sign it, and then later use the
1425         // signature for the commitment_signed message.
1426         let local_chan_balance = 1313;
1427
1428         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1429                 offered: false,
1430                 amount_msat: 3460001,
1431                 cltv_expiry: htlc_cltv,
1432                 payment_hash,
1433                 transaction_output_index: Some(1),
1434         };
1435
1436         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1437
1438         let res = {
1439                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1440                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1441                 let local_chan_signer = local_chan.get_signer();
1442                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1443                         commitment_number,
1444                         95000,
1445                         local_chan_balance,
1446                         local_chan.opt_anchors(), local_funding, remote_funding,
1447                         commit_tx_keys.clone(),
1448                         feerate_per_kw,
1449                         &mut vec![(accepted_htlc_info, ())],
1450                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1451                 );
1452                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1453         };
1454
1455         let commit_signed_msg = msgs::CommitmentSigned {
1456                 channel_id: chan.2,
1457                 signature: res.0,
1458                 htlc_signatures: res.1
1459         };
1460
1461         // Send the commitment_signed message to the nodes[1].
1462         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1463         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1464
1465         // Send the RAA to nodes[1].
1466         let raa_msg = msgs::RevokeAndACK {
1467                 channel_id: chan.2,
1468                 per_commitment_secret: local_secret,
1469                 next_per_commitment_point: next_local_point
1470         };
1471         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1472
1473         let events = nodes[1].node.get_and_clear_pending_msg_events();
1474         assert_eq!(events.len(), 1);
1475         // Make sure the HTLC failed in the way we expect.
1476         match events[0] {
1477                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1478                         assert_eq!(update_fail_htlcs.len(), 1);
1479                         update_fail_htlcs[0].clone()
1480                 },
1481                 _ => panic!("Unexpected event"),
1482         };
1483         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1484                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1485
1486         check_added_monitors!(nodes[1], 2);
1487 }
1488
1489 #[test]
1490 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1491         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1492         // Set the fee rate for the channel very high, to the point where the fundee
1493         // sending any above-dust amount would result in a channel reserve violation.
1494         // In this test we check that we would be prevented from sending an HTLC in
1495         // this situation.
1496         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1497         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1498         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1499         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1500
1501         let opt_anchors = false;
1502
1503         let mut push_amt = 100_000_000;
1504         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1505         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1506
1507         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1508
1509         // Sending exactly enough to hit the reserve amount should be accepted
1510         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1511                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1512         }
1513
1514         // However one more HTLC should be significantly over the reserve amount and fail.
1515         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1516         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1517                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1518         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1519         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1520 }
1521
1522 #[test]
1523 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1524         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1525         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1526         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1527         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1528         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1529
1530         let opt_anchors = false;
1531
1532         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1533         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1534         // transaction fee with 0 HTLCs (183 sats)).
1535         let mut push_amt = 100_000_000;
1536         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1537         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1538         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1539
1540         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1541         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1542                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1543         }
1544
1545         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1546         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1547         let secp_ctx = Secp256k1::new();
1548         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1549         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1550         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1551         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1552         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1553         let msg = msgs::UpdateAddHTLC {
1554                 channel_id: chan.2,
1555                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1556                 amount_msat: htlc_msat,
1557                 payment_hash: payment_hash,
1558                 cltv_expiry: htlc_cltv,
1559                 onion_routing_packet: onion_packet,
1560         };
1561
1562         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1563         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1564         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1565         assert_eq!(nodes[0].node.list_channels().len(), 0);
1566         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1567         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1568         check_added_monitors!(nodes[0], 1);
1569         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() });
1570 }
1571
1572 #[test]
1573 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1574         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1575         // calculating our commitment transaction fee (this was previously broken).
1576         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1577         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1578
1579         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1580         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1581         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1582
1583         let opt_anchors = false;
1584
1585         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1586         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1587         // transaction fee with 0 HTLCs (183 sats)).
1588         let mut push_amt = 100_000_000;
1589         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1590         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1591         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1592
1593         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1594                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1595         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1596         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1597         // commitment transaction fee.
1598         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1599
1600         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1601         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1602                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1603         }
1604
1605         // One more than the dust amt should fail, however.
1606         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1607         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1608                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1609 }
1610
1611 #[test]
1612 fn test_chan_init_feerate_unaffordability() {
1613         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1614         // channel reserve and feerate requirements.
1615         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1616         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1617         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1618         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1619         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1620
1621         let opt_anchors = false;
1622
1623         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1624         // HTLC.
1625         let mut push_amt = 100_000_000;
1626         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1627         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1628                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1629
1630         // During open, we don't have a "counterparty channel reserve" to check against, so that
1631         // requirement only comes into play on the open_channel handling side.
1632         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1633         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1634         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1635         open_channel_msg.push_msat += 1;
1636         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1637
1638         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1639         assert_eq!(msg_events.len(), 1);
1640         match msg_events[0] {
1641                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1642                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1643                 },
1644                 _ => panic!("Unexpected event"),
1645         }
1646 }
1647
1648 #[test]
1649 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1650         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1651         // calculating our counterparty's commitment transaction fee (this was previously broken).
1652         let chanmon_cfgs = create_chanmon_cfgs(2);
1653         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1654         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1655         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1656         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1657
1658         let payment_amt = 46000; // Dust amount
1659         // In the previous code, these first four payments would succeed.
1660         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1661         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1662         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1663         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1664
1665         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1666         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1667         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1668         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1669         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1670         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1671
1672         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1673         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1674         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1675         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1676 }
1677
1678 #[test]
1679 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1680         let chanmon_cfgs = create_chanmon_cfgs(3);
1681         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1682         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1683         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1684         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1685         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1686
1687         let feemsat = 239;
1688         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1689         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1690         let feerate = get_feerate!(nodes[0], chan.2);
1691         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1692
1693         // Add a 2* and +1 for the fee spike reserve.
1694         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1695         let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1696         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1697
1698         // Add a pending HTLC.
1699         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1700         let payment_event_1 = {
1701                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1702                 check_added_monitors!(nodes[0], 1);
1703
1704                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1705                 assert_eq!(events.len(), 1);
1706                 SendEvent::from_event(events.remove(0))
1707         };
1708         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1709
1710         // Attempt to trigger a channel reserve violation --> payment failure.
1711         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1712         let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1713         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1714         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1715
1716         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1717         let secp_ctx = Secp256k1::new();
1718         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1719         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1720         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1721         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1722         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1723         let msg = msgs::UpdateAddHTLC {
1724                 channel_id: chan.2,
1725                 htlc_id: 1,
1726                 amount_msat: htlc_msat + 1,
1727                 payment_hash: our_payment_hash_1,
1728                 cltv_expiry: htlc_cltv,
1729                 onion_routing_packet: onion_packet,
1730         };
1731
1732         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1733         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1734         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1735         assert_eq!(nodes[1].node.list_channels().len(), 1);
1736         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1737         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1738         check_added_monitors!(nodes[1], 1);
1739         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1740 }
1741
1742 #[test]
1743 fn test_inbound_outbound_capacity_is_not_zero() {
1744         let chanmon_cfgs = create_chanmon_cfgs(2);
1745         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1746         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1747         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1748         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1749         let channels0 = node_chanmgrs[0].list_channels();
1750         let channels1 = node_chanmgrs[1].list_channels();
1751         assert_eq!(channels0.len(), 1);
1752         assert_eq!(channels1.len(), 1);
1753
1754         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1755         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1756         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1757
1758         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1759         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1760 }
1761
1762 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1763         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1764 }
1765
1766 #[test]
1767 fn test_channel_reserve_holding_cell_htlcs() {
1768         let chanmon_cfgs = create_chanmon_cfgs(3);
1769         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1770         // When this test was written, the default base fee floated based on the HTLC count.
1771         // It is now fixed, so we simply set the fee to the expected value here.
1772         let mut config = test_default_channel_config();
1773         config.channel_config.forwarding_fee_base_msat = 239;
1774         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1775         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1776         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1777         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1778
1779         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1780         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1781
1782         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1783         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1784
1785         macro_rules! expect_forward {
1786                 ($node: expr) => {{
1787                         let mut events = $node.node.get_and_clear_pending_msg_events();
1788                         assert_eq!(events.len(), 1);
1789                         check_added_monitors!($node, 1);
1790                         let payment_event = SendEvent::from_event(events.remove(0));
1791                         payment_event
1792                 }}
1793         }
1794
1795         let feemsat = 239; // set above
1796         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1797         let feerate = get_feerate!(nodes[0], chan_1.2);
1798         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1799
1800         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1801
1802         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1803         {
1804                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1805                         .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1806                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0, TEST_FINAL_CLTV);
1807                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1808                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1809
1810                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1811                         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)));
1812                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1813                 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);
1814         }
1815
1816         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1817         // nodes[0]'s wealth
1818         loop {
1819                 let amt_msat = recv_value_0 + total_fee_msat;
1820                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1821                 // Also, ensure that each payment has enough to be over the dust limit to
1822                 // ensure it'll be included in each commit tx fee calculation.
1823                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1824                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1825                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1826                         break;
1827                 }
1828
1829                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1830                         .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1831                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1832                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1833                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1834
1835                 let (stat01_, stat11_, stat12_, stat22_) = (
1836                         get_channel_value_stat!(nodes[0], chan_1.2),
1837                         get_channel_value_stat!(nodes[1], chan_1.2),
1838                         get_channel_value_stat!(nodes[1], chan_2.2),
1839                         get_channel_value_stat!(nodes[2], chan_2.2),
1840                 );
1841
1842                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1843                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1844                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1845                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1846                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1847         }
1848
1849         // adding pending output.
1850         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1851         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1852         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1853         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1854         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1855         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1856         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1857         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1858         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1859         // policy.
1860         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1861         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1862         let amt_msat_1 = recv_value_1 + total_fee_msat;
1863
1864         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);
1865         let payment_event_1 = {
1866                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1867                 check_added_monitors!(nodes[0], 1);
1868
1869                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1870                 assert_eq!(events.len(), 1);
1871                 SendEvent::from_event(events.remove(0))
1872         };
1873         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1874
1875         // channel reserve test with htlc pending output > 0
1876         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1877         {
1878                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1879                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1880                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1881                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1882         }
1883
1884         // split the rest to test holding cell
1885         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1886         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1887         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1888         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1889         {
1890                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1891                 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);
1892         }
1893
1894         // now see if they go through on both sides
1895         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);
1896         // but this will stuck in the holding cell
1897         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1898         check_added_monitors!(nodes[0], 0);
1899         let events = nodes[0].node.get_and_clear_pending_events();
1900         assert_eq!(events.len(), 0);
1901
1902         // test with outbound holding cell amount > 0
1903         {
1904                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1905                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1906                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1907                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1908                 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);
1909         }
1910
1911         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);
1912         // this will also stuck in the holding cell
1913         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1914         check_added_monitors!(nodes[0], 0);
1915         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1916         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1917
1918         // flush the pending htlc
1919         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1920         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1921         check_added_monitors!(nodes[1], 1);
1922
1923         // the pending htlc should be promoted to committed
1924         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1925         check_added_monitors!(nodes[0], 1);
1926         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1927
1928         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1929         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1930         // No commitment_signed so get_event_msg's assert(len == 1) passes
1931         check_added_monitors!(nodes[0], 1);
1932
1933         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1934         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1935         check_added_monitors!(nodes[1], 1);
1936
1937         expect_pending_htlcs_forwardable!(nodes[1]);
1938
1939         let ref payment_event_11 = expect_forward!(nodes[1]);
1940         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1941         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1942
1943         expect_pending_htlcs_forwardable!(nodes[2]);
1944         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1945
1946         // flush the htlcs in the holding cell
1947         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1948         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1949         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1950         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1951         expect_pending_htlcs_forwardable!(nodes[1]);
1952
1953         let ref payment_event_3 = expect_forward!(nodes[1]);
1954         assert_eq!(payment_event_3.msgs.len(), 2);
1955         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1956         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1957
1958         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1959         expect_pending_htlcs_forwardable!(nodes[2]);
1960
1961         let events = nodes[2].node.get_and_clear_pending_events();
1962         assert_eq!(events.len(), 2);
1963         match events[0] {
1964                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1965                         assert_eq!(our_payment_hash_21, *payment_hash);
1966                         assert_eq!(recv_value_21, amount_msat);
1967                         match &purpose {
1968                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1969                                         assert!(payment_preimage.is_none());
1970                                         assert_eq!(our_payment_secret_21, *payment_secret);
1971                                 },
1972                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1973                         }
1974                 },
1975                 _ => panic!("Unexpected event"),
1976         }
1977         match events[1] {
1978                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1979                         assert_eq!(our_payment_hash_22, *payment_hash);
1980                         assert_eq!(recv_value_22, amount_msat);
1981                         match &purpose {
1982                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1983                                         assert!(payment_preimage.is_none());
1984                                         assert_eq!(our_payment_secret_22, *payment_secret);
1985                                 },
1986                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1987                         }
1988                 },
1989                 _ => panic!("Unexpected event"),
1990         }
1991
1992         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1993         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1994         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1995
1996         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1997         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1998         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1999
2000         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2001         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);
2002         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2003         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2004         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2005
2006         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2007         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2008 }
2009
2010 #[test]
2011 fn channel_reserve_in_flight_removes() {
2012         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2013         // can send to its counterparty, but due to update ordering, the other side may not yet have
2014         // considered those HTLCs fully removed.
2015         // This tests that we don't count HTLCs which will not be included in the next remote
2016         // commitment transaction towards the reserve value (as it implies no commitment transaction
2017         // will be generated which violates the remote reserve value).
2018         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2019         // To test this we:
2020         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2021         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2022         //    you only consider the value of the first HTLC, it may not),
2023         //  * start routing a third HTLC from A to B,
2024         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2025         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2026         //  * deliver the first fulfill from B
2027         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2028         //    claim,
2029         //  * deliver A's response CS and RAA.
2030         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2031         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2032         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2033         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2034         let chanmon_cfgs = create_chanmon_cfgs(2);
2035         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2036         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2037         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2038         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2039
2040         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2041         // Route the first two HTLCs.
2042         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2043         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2044         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2045
2046         // Start routing the third HTLC (this is just used to get everyone in the right state).
2047         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2048         let send_1 = {
2049                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2050                 check_added_monitors!(nodes[0], 1);
2051                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2052                 assert_eq!(events.len(), 1);
2053                 SendEvent::from_event(events.remove(0))
2054         };
2055
2056         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2057         // initial fulfill/CS.
2058         nodes[1].node.claim_funds(payment_preimage_1);
2059         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2060         check_added_monitors!(nodes[1], 1);
2061         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2062
2063         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2064         // remove the second HTLC when we send the HTLC back from B to A.
2065         nodes[1].node.claim_funds(payment_preimage_2);
2066         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2067         check_added_monitors!(nodes[1], 1);
2068         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2069
2070         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2071         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2072         check_added_monitors!(nodes[0], 1);
2073         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2074         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2075
2076         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2077         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2078         check_added_monitors!(nodes[1], 1);
2079         // B is already AwaitingRAA, so cant generate a CS here
2080         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2081
2082         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2083         check_added_monitors!(nodes[1], 1);
2084         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2085
2086         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2087         check_added_monitors!(nodes[0], 1);
2088         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2089
2090         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2091         check_added_monitors!(nodes[1], 1);
2092         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2093
2094         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2095         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2096         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2097         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2098         // on-chain as necessary).
2099         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2100         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2101         check_added_monitors!(nodes[0], 1);
2102         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2103         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2104
2105         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2106         check_added_monitors!(nodes[1], 1);
2107         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2108
2109         expect_pending_htlcs_forwardable!(nodes[1]);
2110         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2111
2112         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2113         // resolve the second HTLC from A's point of view.
2114         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2115         check_added_monitors!(nodes[0], 1);
2116         expect_payment_path_successful!(nodes[0]);
2117         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2118
2119         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2120         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2121         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2122         let send_2 = {
2123                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2124                 check_added_monitors!(nodes[1], 1);
2125                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2126                 assert_eq!(events.len(), 1);
2127                 SendEvent::from_event(events.remove(0))
2128         };
2129
2130         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2131         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2132         check_added_monitors!(nodes[0], 1);
2133         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2134
2135         // Now just resolve all the outstanding messages/HTLCs for completeness...
2136
2137         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2138         check_added_monitors!(nodes[1], 1);
2139         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2140
2141         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2142         check_added_monitors!(nodes[1], 1);
2143
2144         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2145         check_added_monitors!(nodes[0], 1);
2146         expect_payment_path_successful!(nodes[0]);
2147         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2148
2149         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2150         check_added_monitors!(nodes[1], 1);
2151         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2152
2153         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2154         check_added_monitors!(nodes[0], 1);
2155
2156         expect_pending_htlcs_forwardable!(nodes[0]);
2157         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2158
2159         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2160         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2161 }
2162
2163 #[test]
2164 fn channel_monitor_network_test() {
2165         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2166         // tests that ChannelMonitor is able to recover from various states.
2167         let chanmon_cfgs = create_chanmon_cfgs(5);
2168         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2169         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2170         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2171
2172         // Create some initial channels
2173         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2174         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2175         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2176         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2177
2178         // Make sure all nodes are at the same starting height
2179         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2180         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2181         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2182         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2183         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2184
2185         // Rebalance the network a bit by relaying one payment through all the channels...
2186         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2187         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2188         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2189         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2190
2191         // Simple case with no pending HTLCs:
2192         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2193         check_added_monitors!(nodes[1], 1);
2194         check_closed_broadcast!(nodes[1], true);
2195         {
2196                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2197                 assert_eq!(node_txn.len(), 1);
2198                 mine_transaction(&nodes[0], &node_txn[0]);
2199                 check_added_monitors!(nodes[0], 1);
2200                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2201         }
2202         check_closed_broadcast!(nodes[0], true);
2203         assert_eq!(nodes[0].node.list_channels().len(), 0);
2204         assert_eq!(nodes[1].node.list_channels().len(), 1);
2205         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2206         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2207
2208         // One pending HTLC is discarded by the force-close:
2209         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2210
2211         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2212         // broadcasted until we reach the timelock time).
2213         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2214         check_closed_broadcast!(nodes[1], true);
2215         check_added_monitors!(nodes[1], 1);
2216         {
2217                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2218                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2219                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2220                 mine_transaction(&nodes[2], &node_txn[0]);
2221                 check_added_monitors!(nodes[2], 1);
2222                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2223         }
2224         check_closed_broadcast!(nodes[2], true);
2225         assert_eq!(nodes[1].node.list_channels().len(), 0);
2226         assert_eq!(nodes[2].node.list_channels().len(), 1);
2227         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2228         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2229
2230         macro_rules! claim_funds {
2231                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2232                         {
2233                                 $node.node.claim_funds($preimage);
2234                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2235                                 check_added_monitors!($node, 1);
2236
2237                                 let events = $node.node.get_and_clear_pending_msg_events();
2238                                 assert_eq!(events.len(), 1);
2239                                 match events[0] {
2240                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2241                                                 assert!(update_add_htlcs.is_empty());
2242                                                 assert!(update_fail_htlcs.is_empty());
2243                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2244                                         },
2245                                         _ => panic!("Unexpected event"),
2246                                 };
2247                         }
2248                 }
2249         }
2250
2251         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2252         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2253         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2254         check_added_monitors!(nodes[2], 1);
2255         check_closed_broadcast!(nodes[2], true);
2256         let node2_commitment_txid;
2257         {
2258                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2259                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2260                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2261                 node2_commitment_txid = node_txn[0].txid();
2262
2263                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2264                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2265                 mine_transaction(&nodes[3], &node_txn[0]);
2266                 check_added_monitors!(nodes[3], 1);
2267                 check_preimage_claim(&nodes[3], &node_txn);
2268         }
2269         check_closed_broadcast!(nodes[3], true);
2270         assert_eq!(nodes[2].node.list_channels().len(), 0);
2271         assert_eq!(nodes[3].node.list_channels().len(), 1);
2272         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2273         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2274
2275         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2276         // confusing us in the following tests.
2277         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2278
2279         // One pending HTLC to time out:
2280         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2281         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2282         // buffer space).
2283
2284         let (close_chan_update_1, close_chan_update_2) = {
2285                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2286                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2287                 assert_eq!(events.len(), 2);
2288                 let close_chan_update_1 = match events[0] {
2289                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2290                                 msg.clone()
2291                         },
2292                         _ => panic!("Unexpected event"),
2293                 };
2294                 match events[1] {
2295                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2296                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2297                         },
2298                         _ => panic!("Unexpected event"),
2299                 }
2300                 check_added_monitors!(nodes[3], 1);
2301
2302                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2303                 {
2304                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2305                         node_txn.retain(|tx| {
2306                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2307                                         false
2308                                 } else { true }
2309                         });
2310                 }
2311
2312                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2313
2314                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2315                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2316
2317                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2318                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2319                 assert_eq!(events.len(), 2);
2320                 let close_chan_update_2 = match events[0] {
2321                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2322                                 msg.clone()
2323                         },
2324                         _ => panic!("Unexpected event"),
2325                 };
2326                 match events[1] {
2327                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2328                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2329                         },
2330                         _ => panic!("Unexpected event"),
2331                 }
2332                 check_added_monitors!(nodes[4], 1);
2333                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2334
2335                 mine_transaction(&nodes[4], &node_txn[0]);
2336                 check_preimage_claim(&nodes[4], &node_txn);
2337                 (close_chan_update_1, close_chan_update_2)
2338         };
2339         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2340         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2341         assert_eq!(nodes[3].node.list_channels().len(), 0);
2342         assert_eq!(nodes[4].node.list_channels().len(), 0);
2343
2344         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2345         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2346         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2347 }
2348
2349 #[test]
2350 fn test_justice_tx() {
2351         // Test justice txn built on revoked HTLC-Success tx, against both sides
2352         let mut alice_config = UserConfig::default();
2353         alice_config.channel_handshake_config.announced_channel = true;
2354         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2355         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2356         let mut bob_config = UserConfig::default();
2357         bob_config.channel_handshake_config.announced_channel = true;
2358         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2359         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2360         let user_cfgs = [Some(alice_config), Some(bob_config)];
2361         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2362         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2363         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2364         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2365         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2366         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2367         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2368         // Create some new channels:
2369         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2370
2371         // A pending HTLC which will be revoked:
2372         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2373         // Get the will-be-revoked local txn from nodes[0]
2374         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2375         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2376         assert_eq!(revoked_local_txn[0].input.len(), 1);
2377         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2378         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2379         assert_eq!(revoked_local_txn[1].input.len(), 1);
2380         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2381         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2382         // Revoke the old state
2383         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2384
2385         {
2386                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2387                 {
2388                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2389                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2390                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2391
2392                         check_spends!(node_txn[0], revoked_local_txn[0]);
2393                         node_txn.swap_remove(0);
2394                         node_txn.truncate(1);
2395                 }
2396                 check_added_monitors!(nodes[1], 1);
2397                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2398                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2399
2400                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2401                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2402                 // Verify broadcast of revoked HTLC-timeout
2403                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2404                 check_added_monitors!(nodes[0], 1);
2405                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2406                 // Broadcast revoked HTLC-timeout on node 1
2407                 mine_transaction(&nodes[1], &node_txn[1]);
2408                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2409         }
2410         get_announce_close_broadcast_events(&nodes, 0, 1);
2411
2412         assert_eq!(nodes[0].node.list_channels().len(), 0);
2413         assert_eq!(nodes[1].node.list_channels().len(), 0);
2414
2415         // We test justice_tx build by A on B's revoked HTLC-Success tx
2416         // Create some new channels:
2417         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2418         {
2419                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2420                 node_txn.clear();
2421         }
2422
2423         // A pending HTLC which will be revoked:
2424         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2425         // Get the will-be-revoked local txn from B
2426         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2427         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2428         assert_eq!(revoked_local_txn[0].input.len(), 1);
2429         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2430         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2431         // Revoke the old state
2432         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2433         {
2434                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2435                 {
2436                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2437                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2438                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2439
2440                         check_spends!(node_txn[0], revoked_local_txn[0]);
2441                         node_txn.swap_remove(0);
2442                 }
2443                 check_added_monitors!(nodes[0], 1);
2444                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2445
2446                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2447                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2448                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2449                 check_added_monitors!(nodes[1], 1);
2450                 mine_transaction(&nodes[0], &node_txn[1]);
2451                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2452                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2453         }
2454         get_announce_close_broadcast_events(&nodes, 0, 1);
2455         assert_eq!(nodes[0].node.list_channels().len(), 0);
2456         assert_eq!(nodes[1].node.list_channels().len(), 0);
2457 }
2458
2459 #[test]
2460 fn revoked_output_claim() {
2461         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2462         // transaction is broadcast by its counterparty
2463         let chanmon_cfgs = create_chanmon_cfgs(2);
2464         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2465         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2466         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2467         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2468         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2469         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2470         assert_eq!(revoked_local_txn.len(), 1);
2471         // Only output is the full channel value back to nodes[0]:
2472         assert_eq!(revoked_local_txn[0].output.len(), 1);
2473         // Send a payment through, updating everyone's latest commitment txn
2474         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2475
2476         // Inform nodes[1] that nodes[0] broadcast a stale tx
2477         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2478         check_added_monitors!(nodes[1], 1);
2479         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2480         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2481         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2482
2483         check_spends!(node_txn[0], revoked_local_txn[0]);
2484         check_spends!(node_txn[1], chan_1.3);
2485
2486         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2487         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2488         get_announce_close_broadcast_events(&nodes, 0, 1);
2489         check_added_monitors!(nodes[0], 1);
2490         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2491 }
2492
2493 #[test]
2494 fn claim_htlc_outputs_shared_tx() {
2495         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2496         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2497         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2498         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2499         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2500         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2501
2502         // Create some new channel:
2503         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2504
2505         // Rebalance the network to generate htlc in the two directions
2506         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2507         // 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
2508         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2509         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2510
2511         // Get the will-be-revoked local txn from node[0]
2512         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2513         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2514         assert_eq!(revoked_local_txn[0].input.len(), 1);
2515         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2516         assert_eq!(revoked_local_txn[1].input.len(), 1);
2517         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2518         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2519         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2520
2521         //Revoke the old state
2522         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2523
2524         {
2525                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2526                 check_added_monitors!(nodes[0], 1);
2527                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2528                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2529                 check_added_monitors!(nodes[1], 1);
2530                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2531                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2532                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2533
2534                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2535                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2536
2537                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2538                 check_spends!(node_txn[0], revoked_local_txn[0]);
2539
2540                 let mut witness_lens = BTreeSet::new();
2541                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2542                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2543                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2544                 assert_eq!(witness_lens.len(), 3);
2545                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2546                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2547                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2548
2549                 // Next nodes[1] broadcasts its current local tx state:
2550                 assert_eq!(node_txn[1].input.len(), 1);
2551                 check_spends!(node_txn[1], chan_1.3);
2552
2553                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2554                 // ANTI_REORG_DELAY confirmations.
2555                 mine_transaction(&nodes[1], &node_txn[0]);
2556                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2557                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2558         }
2559         get_announce_close_broadcast_events(&nodes, 0, 1);
2560         assert_eq!(nodes[0].node.list_channels().len(), 0);
2561         assert_eq!(nodes[1].node.list_channels().len(), 0);
2562 }
2563
2564 #[test]
2565 fn claim_htlc_outputs_single_tx() {
2566         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2567         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2568         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2569         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2570         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2571         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2572
2573         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2574
2575         // Rebalance the network to generate htlc in the two directions
2576         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2577         // 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
2578         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2579         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2580         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2581
2582         // Get the will-be-revoked local txn from node[0]
2583         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2584
2585         //Revoke the old state
2586         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2587
2588         {
2589                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2590                 check_added_monitors!(nodes[0], 1);
2591                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2592                 check_added_monitors!(nodes[1], 1);
2593                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2594                 let mut events = nodes[0].node.get_and_clear_pending_events();
2595                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2596                 match events[1] {
2597                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2598                         _ => panic!("Unexpected event"),
2599                 }
2600
2601                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2602                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2603
2604                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2605                 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2606
2607                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2608                 assert_eq!(node_txn[0].input.len(), 1);
2609                 check_spends!(node_txn[0], chan_1.3);
2610                 assert_eq!(node_txn[1].input.len(), 1);
2611                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2612                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2613                 check_spends!(node_txn[1], node_txn[0]);
2614
2615                 // Justice transactions are indices 1-2-4
2616                 assert_eq!(node_txn[2].input.len(), 1);
2617                 assert_eq!(node_txn[3].input.len(), 1);
2618                 assert_eq!(node_txn[4].input.len(), 1);
2619
2620                 check_spends!(node_txn[2], revoked_local_txn[0]);
2621                 check_spends!(node_txn[3], revoked_local_txn[0]);
2622                 check_spends!(node_txn[4], revoked_local_txn[0]);
2623
2624                 let mut witness_lens = BTreeSet::new();
2625                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2626                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2627                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2628                 assert_eq!(witness_lens.len(), 3);
2629                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2630                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2631                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2632
2633                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2634                 // ANTI_REORG_DELAY confirmations.
2635                 mine_transaction(&nodes[1], &node_txn[2]);
2636                 mine_transaction(&nodes[1], &node_txn[3]);
2637                 mine_transaction(&nodes[1], &node_txn[4]);
2638                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2639                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2640         }
2641         get_announce_close_broadcast_events(&nodes, 0, 1);
2642         assert_eq!(nodes[0].node.list_channels().len(), 0);
2643         assert_eq!(nodes[1].node.list_channels().len(), 0);
2644 }
2645
2646 #[test]
2647 fn test_htlc_on_chain_success() {
2648         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2649         // the preimage backward accordingly. So here we test that ChannelManager is
2650         // broadcasting the right event to other nodes in payment path.
2651         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2652         // A --------------------> B ----------------------> C (preimage)
2653         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2654         // commitment transaction was broadcast.
2655         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2656         // towards B.
2657         // B should be able to claim via preimage if A then broadcasts its local tx.
2658         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2659         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2660         // PaymentSent event).
2661
2662         let chanmon_cfgs = create_chanmon_cfgs(3);
2663         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2664         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2665         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2666
2667         // Create some initial channels
2668         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2669         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2670
2671         // Ensure all nodes are at the same height
2672         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2673         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2674         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2675         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2676
2677         // Rebalance the network a bit by relaying one payment through all the channels...
2678         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2679         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2680
2681         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2682         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2683
2684         // Broadcast legit commitment tx from C on B's chain
2685         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2686         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2687         assert_eq!(commitment_tx.len(), 1);
2688         check_spends!(commitment_tx[0], chan_2.3);
2689         nodes[2].node.claim_funds(our_payment_preimage);
2690         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2691         nodes[2].node.claim_funds(our_payment_preimage_2);
2692         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2693         check_added_monitors!(nodes[2], 2);
2694         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2695         assert!(updates.update_add_htlcs.is_empty());
2696         assert!(updates.update_fail_htlcs.is_empty());
2697         assert!(updates.update_fail_malformed_htlcs.is_empty());
2698         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2699
2700         mine_transaction(&nodes[2], &commitment_tx[0]);
2701         check_closed_broadcast!(nodes[2], true);
2702         check_added_monitors!(nodes[2], 1);
2703         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2704         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)
2705         assert_eq!(node_txn.len(), 5);
2706         assert_eq!(node_txn[0], node_txn[3]);
2707         assert_eq!(node_txn[1], node_txn[4]);
2708         assert_eq!(node_txn[2], commitment_tx[0]);
2709         check_spends!(node_txn[0], commitment_tx[0]);
2710         check_spends!(node_txn[1], commitment_tx[0]);
2711         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2712         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2713         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2714         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2715         assert_eq!(node_txn[0].lock_time, 0);
2716         assert_eq!(node_txn[1].lock_time, 0);
2717
2718         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2719         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2720         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2721         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2722         {
2723                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2724                 assert_eq!(added_monitors.len(), 1);
2725                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2726                 added_monitors.clear();
2727         }
2728         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2729         assert_eq!(forwarded_events.len(), 3);
2730         match forwarded_events[0] {
2731                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2732                 _ => panic!("Unexpected event"),
2733         }
2734         let chan_id = Some(chan_1.2);
2735         match forwarded_events[1] {
2736                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2737                         assert_eq!(fee_earned_msat, Some(1000));
2738                         assert_eq!(prev_channel_id, chan_id);
2739                         assert_eq!(claim_from_onchain_tx, true);
2740                         assert_eq!(next_channel_id, Some(chan_2.2));
2741                 },
2742                 _ => panic!()
2743         }
2744         match forwarded_events[2] {
2745                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2746                         assert_eq!(fee_earned_msat, Some(1000));
2747                         assert_eq!(prev_channel_id, chan_id);
2748                         assert_eq!(claim_from_onchain_tx, true);
2749                         assert_eq!(next_channel_id, Some(chan_2.2));
2750                 },
2751                 _ => panic!()
2752         }
2753         let events = nodes[1].node.get_and_clear_pending_msg_events();
2754         {
2755                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2756                 assert_eq!(added_monitors.len(), 2);
2757                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2758                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2759                 added_monitors.clear();
2760         }
2761         assert_eq!(events.len(), 3);
2762         match events[0] {
2763                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2764                 _ => panic!("Unexpected event"),
2765         }
2766         match events[1] {
2767                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2768                 _ => panic!("Unexpected event"),
2769         }
2770
2771         match events[2] {
2772                 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, .. } } => {
2773                         assert!(update_add_htlcs.is_empty());
2774                         assert!(update_fail_htlcs.is_empty());
2775                         assert_eq!(update_fulfill_htlcs.len(), 1);
2776                         assert!(update_fail_malformed_htlcs.is_empty());
2777                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2778                 },
2779                 _ => panic!("Unexpected event"),
2780         };
2781         macro_rules! check_tx_local_broadcast {
2782                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2783                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2784                         assert_eq!(node_txn.len(), 3);
2785                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2786                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2787                         check_spends!(node_txn[1], $commitment_tx);
2788                         check_spends!(node_txn[2], $commitment_tx);
2789                         assert_ne!(node_txn[1].lock_time, 0);
2790                         assert_ne!(node_txn[2].lock_time, 0);
2791                         if $htlc_offered {
2792                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2793                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2794                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2795                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2796                         } else {
2797                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2798                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2799                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2800                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2801                         }
2802                         check_spends!(node_txn[0], $chan_tx);
2803                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2804                         node_txn.clear();
2805                 } }
2806         }
2807         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2808         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2809         // timeout-claim of the output that nodes[2] just claimed via success.
2810         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2811
2812         // Broadcast legit commitment tx from A on B's chain
2813         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2814         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2815         check_spends!(node_a_commitment_tx[0], chan_1.3);
2816         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2817         check_closed_broadcast!(nodes[1], true);
2818         check_added_monitors!(nodes[1], 1);
2819         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2820         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2821         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2822         let commitment_spend =
2823                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2824                         check_spends!(node_txn[1], commitment_tx[0]);
2825                         check_spends!(node_txn[2], commitment_tx[0]);
2826                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2827                         &node_txn[0]
2828                 } else {
2829                         check_spends!(node_txn[0], commitment_tx[0]);
2830                         check_spends!(node_txn[1], commitment_tx[0]);
2831                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2832                         &node_txn[2]
2833                 };
2834
2835         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2836         assert_eq!(commitment_spend.input.len(), 2);
2837         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2838         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2839         assert_eq!(commitment_spend.lock_time, 0);
2840         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2841         check_spends!(node_txn[3], chan_1.3);
2842         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2843         check_spends!(node_txn[4], node_txn[3]);
2844         check_spends!(node_txn[5], node_txn[3]);
2845         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2846         // we already checked the same situation with A.
2847
2848         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2849         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2850         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2851         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2852         check_closed_broadcast!(nodes[0], true);
2853         check_added_monitors!(nodes[0], 1);
2854         let events = nodes[0].node.get_and_clear_pending_events();
2855         assert_eq!(events.len(), 5);
2856         let mut first_claimed = false;
2857         for event in events {
2858                 match event {
2859                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2860                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2861                                         assert!(!first_claimed);
2862                                         first_claimed = true;
2863                                 } else {
2864                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2865                                         assert_eq!(payment_hash, payment_hash_2);
2866                                 }
2867                         },
2868                         Event::PaymentPathSuccessful { .. } => {},
2869                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2870                         _ => panic!("Unexpected event"),
2871                 }
2872         }
2873         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2874 }
2875
2876 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2877         // Test that in case of a unilateral close onchain, we detect the state of output and
2878         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2879         // broadcasting the right event to other nodes in payment path.
2880         // A ------------------> B ----------------------> C (timeout)
2881         //    B's commitment tx                 C's commitment tx
2882         //            \                                  \
2883         //         B's HTLC timeout tx               B's timeout tx
2884
2885         let chanmon_cfgs = create_chanmon_cfgs(3);
2886         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2887         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2888         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2889         *nodes[0].connect_style.borrow_mut() = connect_style;
2890         *nodes[1].connect_style.borrow_mut() = connect_style;
2891         *nodes[2].connect_style.borrow_mut() = connect_style;
2892
2893         // Create some intial channels
2894         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2895         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2896
2897         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2898         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2899         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2900
2901         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2902
2903         // Broadcast legit commitment tx from C on B's chain
2904         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2905         check_spends!(commitment_tx[0], chan_2.3);
2906         nodes[2].node.fail_htlc_backwards(&payment_hash);
2907         check_added_monitors!(nodes[2], 0);
2908         expect_pending_htlcs_forwardable!(nodes[2]);
2909         check_added_monitors!(nodes[2], 1);
2910
2911         let events = nodes[2].node.get_and_clear_pending_msg_events();
2912         assert_eq!(events.len(), 1);
2913         match events[0] {
2914                 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, .. } } => {
2915                         assert!(update_add_htlcs.is_empty());
2916                         assert!(!update_fail_htlcs.is_empty());
2917                         assert!(update_fulfill_htlcs.is_empty());
2918                         assert!(update_fail_malformed_htlcs.is_empty());
2919                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2920                 },
2921                 _ => panic!("Unexpected event"),
2922         };
2923         mine_transaction(&nodes[2], &commitment_tx[0]);
2924         check_closed_broadcast!(nodes[2], true);
2925         check_added_monitors!(nodes[2], 1);
2926         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2927         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2928         assert_eq!(node_txn.len(), 1);
2929         check_spends!(node_txn[0], chan_2.3);
2930         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2931
2932         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2933         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2934         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2935         mine_transaction(&nodes[1], &commitment_tx[0]);
2936         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2937         let timeout_tx;
2938         {
2939                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2940                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2941                 assert_eq!(node_txn[0], node_txn[3]);
2942                 assert_eq!(node_txn[1], node_txn[4]);
2943
2944                 check_spends!(node_txn[2], commitment_tx[0]);
2945                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2946
2947                 check_spends!(node_txn[0], chan_2.3);
2948                 check_spends!(node_txn[1], node_txn[0]);
2949                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2950                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2951
2952                 timeout_tx = node_txn[2].clone();
2953                 node_txn.clear();
2954         }
2955
2956         mine_transaction(&nodes[1], &timeout_tx);
2957         check_added_monitors!(nodes[1], 1);
2958         check_closed_broadcast!(nodes[1], true);
2959         {
2960                 // B will rebroadcast a fee-bumped timeout transaction here.
2961                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2962                 assert_eq!(node_txn.len(), 1);
2963                 check_spends!(node_txn[0], commitment_tx[0]);
2964         }
2965
2966         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2967         {
2968                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2969                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2970                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2971                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2972                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2973                 if node_txn.len() == 1 {
2974                         check_spends!(node_txn[0], chan_2.3);
2975                 } else {
2976                         assert_eq!(node_txn.len(), 0);
2977                 }
2978         }
2979
2980         expect_pending_htlcs_forwardable!(nodes[1]);
2981         check_added_monitors!(nodes[1], 1);
2982         let events = nodes[1].node.get_and_clear_pending_msg_events();
2983         assert_eq!(events.len(), 1);
2984         match events[0] {
2985                 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, .. } } => {
2986                         assert!(update_add_htlcs.is_empty());
2987                         assert!(!update_fail_htlcs.is_empty());
2988                         assert!(update_fulfill_htlcs.is_empty());
2989                         assert!(update_fail_malformed_htlcs.is_empty());
2990                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2991                 },
2992                 _ => panic!("Unexpected event"),
2993         };
2994
2995         // Broadcast legit commitment tx from B on A's chain
2996         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2997         check_spends!(commitment_tx[0], chan_1.3);
2998
2999         mine_transaction(&nodes[0], &commitment_tx[0]);
3000         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3001
3002         check_closed_broadcast!(nodes[0], true);
3003         check_added_monitors!(nodes[0], 1);
3004         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3005         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3006         assert_eq!(node_txn.len(), 2);
3007         check_spends!(node_txn[0], chan_1.3);
3008         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3009         check_spends!(node_txn[1], commitment_tx[0]);
3010         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3011 }
3012
3013 #[test]
3014 fn test_htlc_on_chain_timeout() {
3015         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3016         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3017         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3018 }
3019
3020 #[test]
3021 fn test_simple_commitment_revoked_fail_backward() {
3022         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3023         // and fail backward accordingly.
3024
3025         let chanmon_cfgs = create_chanmon_cfgs(3);
3026         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3027         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3028         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3029
3030         // Create some initial channels
3031         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3032         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3033
3034         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3035         // Get the will-be-revoked local txn from nodes[2]
3036         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3037         // Revoke the old state
3038         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3039
3040         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3041
3042         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3043         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3044         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3045         check_added_monitors!(nodes[1], 1);
3046         check_closed_broadcast!(nodes[1], true);
3047
3048         expect_pending_htlcs_forwardable!(nodes[1]);
3049         check_added_monitors!(nodes[1], 1);
3050         let events = nodes[1].node.get_and_clear_pending_msg_events();
3051         assert_eq!(events.len(), 1);
3052         match events[0] {
3053                 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, .. } } => {
3054                         assert!(update_add_htlcs.is_empty());
3055                         assert_eq!(update_fail_htlcs.len(), 1);
3056                         assert!(update_fulfill_htlcs.is_empty());
3057                         assert!(update_fail_malformed_htlcs.is_empty());
3058                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3059
3060                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3061                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3062                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3063                 },
3064                 _ => panic!("Unexpected event"),
3065         }
3066 }
3067
3068 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3069         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3070         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3071         // commitment transaction anymore.
3072         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3073         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3074         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3075         // technically disallowed and we should probably handle it reasonably.
3076         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3077         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3078         // transactions:
3079         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3080         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3081         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3082         //   and once they revoke the previous commitment transaction (allowing us to send a new
3083         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3084         let chanmon_cfgs = create_chanmon_cfgs(3);
3085         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3086         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3087         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3088
3089         // Create some initial channels
3090         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3091         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3092
3093         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 });
3094         // Get the will-be-revoked local txn from nodes[2]
3095         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3096         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3097         // Revoke the old state
3098         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3099
3100         let value = if use_dust {
3101                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3102                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3103                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3104         } else { 3000000 };
3105
3106         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3107         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3108         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3109
3110         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3111         expect_pending_htlcs_forwardable!(nodes[2]);
3112         check_added_monitors!(nodes[2], 1);
3113         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3114         assert!(updates.update_add_htlcs.is_empty());
3115         assert!(updates.update_fulfill_htlcs.is_empty());
3116         assert!(updates.update_fail_malformed_htlcs.is_empty());
3117         assert_eq!(updates.update_fail_htlcs.len(), 1);
3118         assert!(updates.update_fee.is_none());
3119         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3120         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3121         // Drop the last RAA from 3 -> 2
3122
3123         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3124         expect_pending_htlcs_forwardable!(nodes[2]);
3125         check_added_monitors!(nodes[2], 1);
3126         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3127         assert!(updates.update_add_htlcs.is_empty());
3128         assert!(updates.update_fulfill_htlcs.is_empty());
3129         assert!(updates.update_fail_malformed_htlcs.is_empty());
3130         assert_eq!(updates.update_fail_htlcs.len(), 1);
3131         assert!(updates.update_fee.is_none());
3132         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3133         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3134         check_added_monitors!(nodes[1], 1);
3135         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3136         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3137         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3138         check_added_monitors!(nodes[2], 1);
3139
3140         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3141         expect_pending_htlcs_forwardable!(nodes[2]);
3142         check_added_monitors!(nodes[2], 1);
3143         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3144         assert!(updates.update_add_htlcs.is_empty());
3145         assert!(updates.update_fulfill_htlcs.is_empty());
3146         assert!(updates.update_fail_malformed_htlcs.is_empty());
3147         assert_eq!(updates.update_fail_htlcs.len(), 1);
3148         assert!(updates.update_fee.is_none());
3149         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3150         // At this point first_payment_hash has dropped out of the latest two commitment
3151         // transactions that nodes[1] is tracking...
3152         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3153         check_added_monitors!(nodes[1], 1);
3154         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3155         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3156         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3157         check_added_monitors!(nodes[2], 1);
3158
3159         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3160         // on nodes[2]'s RAA.
3161         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3162         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3163         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3164         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3165         check_added_monitors!(nodes[1], 0);
3166
3167         if deliver_bs_raa {
3168                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3169                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3170                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3171                 check_added_monitors!(nodes[1], 1);
3172                 let events = nodes[1].node.get_and_clear_pending_events();
3173                 assert_eq!(events.len(), 1);
3174                 match events[0] {
3175                         Event::PendingHTLCsForwardable { .. } => { },
3176                         _ => panic!("Unexpected event"),
3177                 };
3178                 // Deliberately don't process the pending fail-back so they all fail back at once after
3179                 // block connection just like the !deliver_bs_raa case
3180         }
3181
3182         let mut failed_htlcs = HashSet::new();
3183         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3184
3185         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3186         check_added_monitors!(nodes[1], 1);
3187         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3188         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3189
3190         let events = nodes[1].node.get_and_clear_pending_events();
3191         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3192         match events[0] {
3193                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3194                 _ => panic!("Unexepected event"),
3195         }
3196         match events[1] {
3197                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3198                         assert_eq!(*payment_hash, fourth_payment_hash);
3199                 },
3200                 _ => panic!("Unexpected event"),
3201         }
3202         if !deliver_bs_raa {
3203                 match events[2] {
3204                         Event::PaymentFailed { ref payment_hash, .. } => {
3205                                 assert_eq!(*payment_hash, fourth_payment_hash);
3206                         },
3207                         _ => panic!("Unexpected event"),
3208                 }
3209                 match events[3] {
3210                         Event::PendingHTLCsForwardable { .. } => { },
3211                         _ => panic!("Unexpected event"),
3212                 };
3213         }
3214         nodes[1].node.process_pending_htlc_forwards();
3215         check_added_monitors!(nodes[1], 1);
3216
3217         let events = nodes[1].node.get_and_clear_pending_msg_events();
3218         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3219         match events[if deliver_bs_raa { 1 } else { 0 }] {
3220                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3221                 _ => panic!("Unexpected event"),
3222         }
3223         match events[if deliver_bs_raa { 2 } else { 1 }] {
3224                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3225                         assert_eq!(channel_id, chan_2.2);
3226                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3227                 },
3228                 _ => panic!("Unexpected event"),
3229         }
3230         if deliver_bs_raa {
3231                 match events[0] {
3232                         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, .. } } => {
3233                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3234                                 assert_eq!(update_add_htlcs.len(), 1);
3235                                 assert!(update_fulfill_htlcs.is_empty());
3236                                 assert!(update_fail_htlcs.is_empty());
3237                                 assert!(update_fail_malformed_htlcs.is_empty());
3238                         },
3239                         _ => panic!("Unexpected event"),
3240                 }
3241         }
3242         match events[if deliver_bs_raa { 3 } else { 2 }] {
3243                 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, .. } } => {
3244                         assert!(update_add_htlcs.is_empty());
3245                         assert_eq!(update_fail_htlcs.len(), 3);
3246                         assert!(update_fulfill_htlcs.is_empty());
3247                         assert!(update_fail_malformed_htlcs.is_empty());
3248                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3249
3250                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3251                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3252                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3253
3254                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3255
3256                         let events = nodes[0].node.get_and_clear_pending_events();
3257                         assert_eq!(events.len(), 3);
3258                         match events[0] {
3259                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3260                                         assert!(failed_htlcs.insert(payment_hash.0));
3261                                         // If we delivered B's RAA we got an unknown preimage error, not something
3262                                         // that we should update our routing table for.
3263                                         if !deliver_bs_raa {
3264                                                 assert!(network_update.is_some());
3265                                         }
3266                                 },
3267                                 _ => panic!("Unexpected event"),
3268                         }
3269                         match events[1] {
3270                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3271                                         assert!(failed_htlcs.insert(payment_hash.0));
3272                                         assert!(network_update.is_some());
3273                                 },
3274                                 _ => panic!("Unexpected event"),
3275                         }
3276                         match events[2] {
3277                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3278                                         assert!(failed_htlcs.insert(payment_hash.0));
3279                                         assert!(network_update.is_some());
3280                                 },
3281                                 _ => panic!("Unexpected event"),
3282                         }
3283                 },
3284                 _ => panic!("Unexpected event"),
3285         }
3286
3287         assert!(failed_htlcs.contains(&first_payment_hash.0));
3288         assert!(failed_htlcs.contains(&second_payment_hash.0));
3289         assert!(failed_htlcs.contains(&third_payment_hash.0));
3290 }
3291
3292 #[test]
3293 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3294         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3295         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3296         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3297         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3298 }
3299
3300 #[test]
3301 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3302         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3303         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3304         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3305         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3306 }
3307
3308 #[test]
3309 fn fail_backward_pending_htlc_upon_channel_failure() {
3310         let chanmon_cfgs = create_chanmon_cfgs(2);
3311         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3312         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3313         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3314         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3315
3316         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3317         {
3318                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3319                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3320                 check_added_monitors!(nodes[0], 1);
3321
3322                 let payment_event = {
3323                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3324                         assert_eq!(events.len(), 1);
3325                         SendEvent::from_event(events.remove(0))
3326                 };
3327                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3328                 assert_eq!(payment_event.msgs.len(), 1);
3329         }
3330
3331         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3332         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3333         {
3334                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3335                 check_added_monitors!(nodes[0], 0);
3336
3337                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3338         }
3339
3340         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3341         {
3342                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3343
3344                 let secp_ctx = Secp256k1::new();
3345                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3346                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3347                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3348                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3349                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3350
3351                 // Send a 0-msat update_add_htlc to fail the channel.
3352                 let update_add_htlc = msgs::UpdateAddHTLC {
3353                         channel_id: chan.2,
3354                         htlc_id: 0,
3355                         amount_msat: 0,
3356                         payment_hash,
3357                         cltv_expiry,
3358                         onion_routing_packet,
3359                 };
3360                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3361         }
3362         let events = nodes[0].node.get_and_clear_pending_events();
3363         assert_eq!(events.len(), 2);
3364         // Check that Alice fails backward the pending HTLC from the second payment.
3365         match events[0] {
3366                 Event::PaymentPathFailed { payment_hash, .. } => {
3367                         assert_eq!(payment_hash, failed_payment_hash);
3368                 },
3369                 _ => panic!("Unexpected event"),
3370         }
3371         match events[1] {
3372                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3373                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3374                 },
3375                 _ => panic!("Unexpected event {:?}", events[1]),
3376         }
3377         check_closed_broadcast!(nodes[0], true);
3378         check_added_monitors!(nodes[0], 1);
3379 }
3380
3381 #[test]
3382 fn test_htlc_ignore_latest_remote_commitment() {
3383         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3384         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3385         let chanmon_cfgs = create_chanmon_cfgs(2);
3386         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3387         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3388         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3389         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3390
3391         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3392         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3393         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3394         check_closed_broadcast!(nodes[0], true);
3395         check_added_monitors!(nodes[0], 1);
3396         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3397
3398         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3399         assert_eq!(node_txn.len(), 3);
3400         assert_eq!(node_txn[0], node_txn[1]);
3401
3402         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3403         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3404         check_closed_broadcast!(nodes[1], true);
3405         check_added_monitors!(nodes[1], 1);
3406         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3407
3408         // Duplicate the connect_block call since this may happen due to other listeners
3409         // registering new transactions
3410         header.prev_blockhash = header.block_hash();
3411         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3412 }
3413
3414 #[test]
3415 fn test_force_close_fail_back() {
3416         // Check which HTLCs are failed-backwards on channel force-closure
3417         let chanmon_cfgs = create_chanmon_cfgs(3);
3418         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3419         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3420         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3421         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3422         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3423
3424         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3425
3426         let mut payment_event = {
3427                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3428                 check_added_monitors!(nodes[0], 1);
3429
3430                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3431                 assert_eq!(events.len(), 1);
3432                 SendEvent::from_event(events.remove(0))
3433         };
3434
3435         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3436         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3437
3438         expect_pending_htlcs_forwardable!(nodes[1]);
3439
3440         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3441         assert_eq!(events_2.len(), 1);
3442         payment_event = SendEvent::from_event(events_2.remove(0));
3443         assert_eq!(payment_event.msgs.len(), 1);
3444
3445         check_added_monitors!(nodes[1], 1);
3446         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3447         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3448         check_added_monitors!(nodes[2], 1);
3449         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3450
3451         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3452         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3453         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3454
3455         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3456         check_closed_broadcast!(nodes[2], true);
3457         check_added_monitors!(nodes[2], 1);
3458         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3459         let tx = {
3460                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3461                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3462                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3463                 // back to nodes[1] upon timeout otherwise.
3464                 assert_eq!(node_txn.len(), 1);
3465                 node_txn.remove(0)
3466         };
3467
3468         mine_transaction(&nodes[1], &tx);
3469
3470         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3471         check_closed_broadcast!(nodes[1], true);
3472         check_added_monitors!(nodes[1], 1);
3473         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3474
3475         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3476         {
3477                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3478                         .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);
3479         }
3480         mine_transaction(&nodes[2], &tx);
3481         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3482         assert_eq!(node_txn.len(), 1);
3483         assert_eq!(node_txn[0].input.len(), 1);
3484         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3485         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3486         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3487
3488         check_spends!(node_txn[0], tx);
3489 }
3490
3491 #[test]
3492 fn test_dup_events_on_peer_disconnect() {
3493         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3494         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3495         // as we used to generate the event immediately upon receipt of the payment preimage in the
3496         // update_fulfill_htlc message.
3497
3498         let chanmon_cfgs = create_chanmon_cfgs(2);
3499         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3500         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3501         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3502         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3503
3504         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3505
3506         nodes[1].node.claim_funds(payment_preimage);
3507         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3508         check_added_monitors!(nodes[1], 1);
3509         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3510         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3511         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3512
3513         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3514         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3515
3516         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3517         expect_payment_path_successful!(nodes[0]);
3518 }
3519
3520 #[test]
3521 fn test_peer_disconnected_before_funding_broadcasted() {
3522         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3523         // before the funding transaction has been broadcasted.
3524         let chanmon_cfgs = create_chanmon_cfgs(2);
3525         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3526         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3527         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3528
3529         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3530         // broadcasted, even though it's created by `nodes[0]`.
3531         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();
3532         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3533         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3534         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3535         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3536
3537         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3538         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3539
3540         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3541
3542         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3543         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3544
3545         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3546         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3547         // broadcasted.
3548         {
3549                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3550         }
3551
3552         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3553         // disconnected before the funding transaction was broadcasted.
3554         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3555         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3556
3557         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3558         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3559 }
3560
3561 #[test]
3562 fn test_simple_peer_disconnect() {
3563         // Test that we can reconnect when there are no lost messages
3564         let chanmon_cfgs = create_chanmon_cfgs(3);
3565         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3566         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3567         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3568         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3569         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3570
3571         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3572         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3573         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3574
3575         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3576         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3577         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3578         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3579
3580         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3581         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3582         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3583
3584         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3585         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3586         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3587         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3588
3589         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3590         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3591
3592         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3593         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3594
3595         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3596         {
3597                 let events = nodes[0].node.get_and_clear_pending_events();
3598                 assert_eq!(events.len(), 3);
3599                 match events[0] {
3600                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3601                                 assert_eq!(payment_preimage, payment_preimage_3);
3602                                 assert_eq!(payment_hash, payment_hash_3);
3603                         },
3604                         _ => panic!("Unexpected event"),
3605                 }
3606                 match events[1] {
3607                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3608                                 assert_eq!(payment_hash, payment_hash_5);
3609                                 assert!(rejected_by_dest);
3610                         },
3611                         _ => panic!("Unexpected event"),
3612                 }
3613                 match events[2] {
3614                         Event::PaymentPathSuccessful { .. } => {},
3615                         _ => panic!("Unexpected event"),
3616                 }
3617         }
3618
3619         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3620         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3621 }
3622
3623 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3624         // Test that we can reconnect when in-flight HTLC updates get dropped
3625         let chanmon_cfgs = create_chanmon_cfgs(2);
3626         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3627         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3628         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3629
3630         let mut as_channel_ready = None;
3631         if messages_delivered == 0 {
3632                 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3633                 as_channel_ready = Some(channel_ready);
3634                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3635                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3636                 // it before the channel_reestablish message.
3637         } else {
3638                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3639         }
3640
3641         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3642
3643         let payment_event = {
3644                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3645                 check_added_monitors!(nodes[0], 1);
3646
3647                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3648                 assert_eq!(events.len(), 1);
3649                 SendEvent::from_event(events.remove(0))
3650         };
3651         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3652
3653         if messages_delivered < 2 {
3654                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3655         } else {
3656                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3657                 if messages_delivered >= 3 {
3658                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3659                         check_added_monitors!(nodes[1], 1);
3660                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3661
3662                         if messages_delivered >= 4 {
3663                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3664                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3665                                 check_added_monitors!(nodes[0], 1);
3666
3667                                 if messages_delivered >= 5 {
3668                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3669                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3670                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3671                                         check_added_monitors!(nodes[0], 1);
3672
3673                                         if messages_delivered >= 6 {
3674                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3675                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3676                                                 check_added_monitors!(nodes[1], 1);
3677                                         }
3678                                 }
3679                         }
3680                 }
3681         }
3682
3683         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3684         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3685         if messages_delivered < 3 {
3686                 if simulate_broken_lnd {
3687                         // lnd has a long-standing bug where they send a channel_ready prior to a
3688                         // channel_reestablish if you reconnect prior to channel_ready time.
3689                         //
3690                         // Here we simulate that behavior, delivering a channel_ready immediately on
3691                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3692                         // in `reconnect_nodes` but we currently don't fail based on that.
3693                         //
3694                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3695                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3696                 }
3697                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3698                 // received on either side, both sides will need to resend them.
3699                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3700         } else if messages_delivered == 3 {
3701                 // nodes[0] still wants its RAA + commitment_signed
3702                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3703         } else if messages_delivered == 4 {
3704                 // nodes[0] still wants its commitment_signed
3705                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3706         } else if messages_delivered == 5 {
3707                 // nodes[1] still wants its final RAA
3708                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3709         } else if messages_delivered == 6 {
3710                 // Everything was delivered...
3711                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3712         }
3713
3714         let events_1 = nodes[1].node.get_and_clear_pending_events();
3715         assert_eq!(events_1.len(), 1);
3716         match events_1[0] {
3717                 Event::PendingHTLCsForwardable { .. } => { },
3718                 _ => panic!("Unexpected event"),
3719         };
3720
3721         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3722         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3723         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3724
3725         nodes[1].node.process_pending_htlc_forwards();
3726
3727         let events_2 = nodes[1].node.get_and_clear_pending_events();
3728         assert_eq!(events_2.len(), 1);
3729         match events_2[0] {
3730                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3731                         assert_eq!(payment_hash_1, *payment_hash);
3732                         assert_eq!(amount_msat, 1_000_000);
3733                         match &purpose {
3734                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3735                                         assert!(payment_preimage.is_none());
3736                                         assert_eq!(payment_secret_1, *payment_secret);
3737                                 },
3738                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3739                         }
3740                 },
3741                 _ => panic!("Unexpected event"),
3742         }
3743
3744         nodes[1].node.claim_funds(payment_preimage_1);
3745         check_added_monitors!(nodes[1], 1);
3746         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3747
3748         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3749         assert_eq!(events_3.len(), 1);
3750         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3751                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3752                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3753                         assert!(updates.update_add_htlcs.is_empty());
3754                         assert!(updates.update_fail_htlcs.is_empty());
3755                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3756                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3757                         assert!(updates.update_fee.is_none());
3758                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3759                 },
3760                 _ => panic!("Unexpected event"),
3761         };
3762
3763         if messages_delivered >= 1 {
3764                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3765
3766                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3767                 assert_eq!(events_4.len(), 1);
3768                 match events_4[0] {
3769                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3770                                 assert_eq!(payment_preimage_1, *payment_preimage);
3771                                 assert_eq!(payment_hash_1, *payment_hash);
3772                         },
3773                         _ => panic!("Unexpected event"),
3774                 }
3775
3776                 if messages_delivered >= 2 {
3777                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3778                         check_added_monitors!(nodes[0], 1);
3779                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3780
3781                         if messages_delivered >= 3 {
3782                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3783                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3784                                 check_added_monitors!(nodes[1], 1);
3785
3786                                 if messages_delivered >= 4 {
3787                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3788                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3789                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3790                                         check_added_monitors!(nodes[1], 1);
3791
3792                                         if messages_delivered >= 5 {
3793                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3794                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3795                                                 check_added_monitors!(nodes[0], 1);
3796                                         }
3797                                 }
3798                         }
3799                 }
3800         }
3801
3802         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3803         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3804         if messages_delivered < 2 {
3805                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3806                 if messages_delivered < 1 {
3807                         expect_payment_sent!(nodes[0], payment_preimage_1);
3808                 } else {
3809                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3810                 }
3811         } else if messages_delivered == 2 {
3812                 // nodes[0] still wants its RAA + commitment_signed
3813                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3814         } else if messages_delivered == 3 {
3815                 // nodes[0] still wants its commitment_signed
3816                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3817         } else if messages_delivered == 4 {
3818                 // nodes[1] still wants its final RAA
3819                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3820         } else if messages_delivered == 5 {
3821                 // Everything was delivered...
3822                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3823         }
3824
3825         if messages_delivered == 1 || messages_delivered == 2 {
3826                 expect_payment_path_successful!(nodes[0]);
3827         }
3828
3829         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3830         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3831         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3832
3833         if messages_delivered > 2 {
3834                 expect_payment_path_successful!(nodes[0]);
3835         }
3836
3837         // Channel should still work fine...
3838         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3839         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3840         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3841 }
3842
3843 #[test]
3844 fn test_drop_messages_peer_disconnect_a() {
3845         do_test_drop_messages_peer_disconnect(0, true);
3846         do_test_drop_messages_peer_disconnect(0, false);
3847         do_test_drop_messages_peer_disconnect(1, false);
3848         do_test_drop_messages_peer_disconnect(2, false);
3849 }
3850
3851 #[test]
3852 fn test_drop_messages_peer_disconnect_b() {
3853         do_test_drop_messages_peer_disconnect(3, false);
3854         do_test_drop_messages_peer_disconnect(4, false);
3855         do_test_drop_messages_peer_disconnect(5, false);
3856         do_test_drop_messages_peer_disconnect(6, false);
3857 }
3858
3859 #[test]
3860 fn test_funding_peer_disconnect() {
3861         // Test that we can lock in our funding tx while disconnected
3862         let chanmon_cfgs = create_chanmon_cfgs(2);
3863         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3864         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3865         let persister: test_utils::TestPersister;
3866         let new_chain_monitor: test_utils::TestChainMonitor;
3867         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3868         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3869         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3870
3871         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3872         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3873
3874         confirm_transaction(&nodes[0], &tx);
3875         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3876         assert!(events_1.is_empty());
3877
3878         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3879
3880         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3881         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3882
3883         confirm_transaction(&nodes[1], &tx);
3884         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3885         assert!(events_2.is_empty());
3886
3887         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3888         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3889         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3890         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3891
3892         // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3893         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3894         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3895         assert_eq!(events_3.len(), 1);
3896         let as_channel_ready = match events_3[0] {
3897                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3898                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3899                         msg.clone()
3900                 },
3901                 _ => panic!("Unexpected event {:?}", events_3[0]),
3902         };
3903
3904         // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3905         // announcement_signatures as well as channel_update.
3906         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3907         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3908         assert_eq!(events_4.len(), 3);
3909         let chan_id;
3910         let bs_channel_ready = match events_4[0] {
3911                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3912                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3913                         chan_id = msg.channel_id;
3914                         msg.clone()
3915                 },
3916                 _ => panic!("Unexpected event {:?}", events_4[0]),
3917         };
3918         let bs_announcement_sigs = match events_4[1] {
3919                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3920                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3921                         msg.clone()
3922                 },
3923                 _ => panic!("Unexpected event {:?}", events_4[1]),
3924         };
3925         match events_4[2] {
3926                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3927                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3928                 },
3929                 _ => panic!("Unexpected event {:?}", events_4[2]),
3930         }
3931
3932         // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3933         // generates a duplicative private channel_update
3934         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3935         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3936         assert_eq!(events_5.len(), 1);
3937         match events_5[0] {
3938                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3939                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3940                 },
3941                 _ => panic!("Unexpected event {:?}", events_5[0]),
3942         };
3943
3944         // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3945         // announcement_signatures.
3946         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3947         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3948         assert_eq!(events_6.len(), 1);
3949         let as_announcement_sigs = match events_6[0] {
3950                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3951                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3952                         msg.clone()
3953                 },
3954                 _ => panic!("Unexpected event {:?}", events_6[0]),
3955         };
3956
3957         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3958         // broadcast the channel announcement globally, as well as re-send its (now-public)
3959         // channel_update.
3960         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3961         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3962         assert_eq!(events_7.len(), 1);
3963         let (chan_announcement, as_update) = match events_7[0] {
3964                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3965                         (msg.clone(), update_msg.clone())
3966                 },
3967                 _ => panic!("Unexpected event {:?}", events_7[0]),
3968         };
3969
3970         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3971         // same channel_announcement.
3972         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3973         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3974         assert_eq!(events_8.len(), 1);
3975         let bs_update = match events_8[0] {
3976                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3977                         assert_eq!(*msg, chan_announcement);
3978                         update_msg.clone()
3979                 },
3980                 _ => panic!("Unexpected event {:?}", events_8[0]),
3981         };
3982
3983         // Provide the channel announcement and public updates to the network graph
3984         nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3985         nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
3986         nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
3987
3988         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3989         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3990         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3991
3992         // Check that after deserialization and reconnection we can still generate an identical
3993         // channel_announcement from the cached signatures.
3994         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3995
3996         let nodes_0_serialized = nodes[0].node.encode();
3997         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3998         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3999
4000         persister = test_utils::TestPersister::new();
4001         let keys_manager = &chanmon_cfgs[0].keys_manager;
4002         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);
4003         nodes[0].chain_monitor = &new_chain_monitor;
4004         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4005         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4006                 &mut chan_0_monitor_read, keys_manager).unwrap();
4007         assert!(chan_0_monitor_read.is_empty());
4008
4009         let mut nodes_0_read = &nodes_0_serialized[..];
4010         let (_, nodes_0_deserialized_tmp) = {
4011                 let mut channel_monitors = HashMap::new();
4012                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4013                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4014                         default_config: UserConfig::default(),
4015                         keys_manager,
4016                         fee_estimator: node_cfgs[0].fee_estimator,
4017                         chain_monitor: nodes[0].chain_monitor,
4018                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4019                         logger: nodes[0].logger,
4020                         channel_monitors,
4021                 }).unwrap()
4022         };
4023         nodes_0_deserialized = nodes_0_deserialized_tmp;
4024         assert!(nodes_0_read.is_empty());
4025
4026         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4027         nodes[0].node = &nodes_0_deserialized;
4028         check_added_monitors!(nodes[0], 1);
4029
4030         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4031
4032         // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4033         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4034         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4035         let mut found_announcement = false;
4036         for event in msgs.iter() {
4037                 match event {
4038                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4039                                 if *msg == chan_announcement { found_announcement = true; }
4040                         },
4041                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4042                         _ => panic!("Unexpected event"),
4043                 }
4044         }
4045         assert!(found_announcement);
4046 }
4047
4048 #[test]
4049 fn test_channel_ready_without_best_block_updated() {
4050         // Previously, if we were offline when a funding transaction was locked in, and then we came
4051         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4052         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4053         // channel_ready immediately instead.
4054         let chanmon_cfgs = create_chanmon_cfgs(2);
4055         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4056         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4057         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4058         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4059
4060         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4061
4062         let conf_height = nodes[0].best_block_info().1 + 1;
4063         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4064         let block_txn = [funding_tx];
4065         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4066         let conf_block_header = nodes[0].get_block_header(conf_height);
4067         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4068
4069         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4070         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4071         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4072 }
4073
4074 #[test]
4075 fn test_drop_messages_peer_disconnect_dual_htlc() {
4076         // Test that we can handle reconnecting when both sides of a channel have pending
4077         // commitment_updates when we disconnect.
4078         let chanmon_cfgs = create_chanmon_cfgs(2);
4079         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4080         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4081         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4082         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4083
4084         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4085
4086         // Now try to send a second payment which will fail to send
4087         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4088         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4089         check_added_monitors!(nodes[0], 1);
4090
4091         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4092         assert_eq!(events_1.len(), 1);
4093         match events_1[0] {
4094                 MessageSendEvent::UpdateHTLCs { .. } => {},
4095                 _ => panic!("Unexpected event"),
4096         }
4097
4098         nodes[1].node.claim_funds(payment_preimage_1);
4099         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4100         check_added_monitors!(nodes[1], 1);
4101
4102         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4103         assert_eq!(events_2.len(), 1);
4104         match events_2[0] {
4105                 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 } } => {
4106                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4107                         assert!(update_add_htlcs.is_empty());
4108                         assert_eq!(update_fulfill_htlcs.len(), 1);
4109                         assert!(update_fail_htlcs.is_empty());
4110                         assert!(update_fail_malformed_htlcs.is_empty());
4111                         assert!(update_fee.is_none());
4112
4113                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4114                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4115                         assert_eq!(events_3.len(), 1);
4116                         match events_3[0] {
4117                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4118                                         assert_eq!(*payment_preimage, payment_preimage_1);
4119                                         assert_eq!(*payment_hash, payment_hash_1);
4120                                 },
4121                                 _ => panic!("Unexpected event"),
4122                         }
4123
4124                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4125                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4126                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4127                         check_added_monitors!(nodes[0], 1);
4128                 },
4129                 _ => panic!("Unexpected event"),
4130         }
4131
4132         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4133         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4134
4135         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4136         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4137         assert_eq!(reestablish_1.len(), 1);
4138         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4139         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4140         assert_eq!(reestablish_2.len(), 1);
4141
4142         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4143         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4144         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4145         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4146
4147         assert!(as_resp.0.is_none());
4148         assert!(bs_resp.0.is_none());
4149
4150         assert!(bs_resp.1.is_none());
4151         assert!(bs_resp.2.is_none());
4152
4153         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4154
4155         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4156         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4157         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4158         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4159         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4160         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4161         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4162         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4163         // No commitment_signed so get_event_msg's assert(len == 1) passes
4164         check_added_monitors!(nodes[1], 1);
4165
4166         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4167         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4168         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4169         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4170         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4171         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4172         assert!(bs_second_commitment_signed.update_fee.is_none());
4173         check_added_monitors!(nodes[1], 1);
4174
4175         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4176         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4177         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4178         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4179         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4180         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4181         assert!(as_commitment_signed.update_fee.is_none());
4182         check_added_monitors!(nodes[0], 1);
4183
4184         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4185         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4186         // No commitment_signed so get_event_msg's assert(len == 1) passes
4187         check_added_monitors!(nodes[0], 1);
4188
4189         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4190         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4191         // No commitment_signed so get_event_msg's assert(len == 1) passes
4192         check_added_monitors!(nodes[1], 1);
4193
4194         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4195         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4196         check_added_monitors!(nodes[1], 1);
4197
4198         expect_pending_htlcs_forwardable!(nodes[1]);
4199
4200         let events_5 = nodes[1].node.get_and_clear_pending_events();
4201         assert_eq!(events_5.len(), 1);
4202         match events_5[0] {
4203                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4204                         assert_eq!(payment_hash_2, *payment_hash);
4205                         match &purpose {
4206                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4207                                         assert!(payment_preimage.is_none());
4208                                         assert_eq!(payment_secret_2, *payment_secret);
4209                                 },
4210                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4211                         }
4212                 },
4213                 _ => panic!("Unexpected event"),
4214         }
4215
4216         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4217         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4218         check_added_monitors!(nodes[0], 1);
4219
4220         expect_payment_path_successful!(nodes[0]);
4221         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4222 }
4223
4224 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4225         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4226         // to avoid our counterparty failing the channel.
4227         let chanmon_cfgs = create_chanmon_cfgs(2);
4228         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4229         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4230         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4231
4232         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4233
4234         let our_payment_hash = if send_partial_mpp {
4235                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4236                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4237                 // indicates there are more HTLCs coming.
4238                 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.
4239                 let payment_id = PaymentId([42; 32]);
4240                 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();
4241                 check_added_monitors!(nodes[0], 1);
4242                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4243                 assert_eq!(events.len(), 1);
4244                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4245                 // hop should *not* yet generate any PaymentReceived event(s).
4246                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4247                 our_payment_hash
4248         } else {
4249                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4250         };
4251
4252         let mut block = Block {
4253                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4254                 txdata: vec![],
4255         };
4256         connect_block(&nodes[0], &block);
4257         connect_block(&nodes[1], &block);
4258         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4259         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4260                 block.header.prev_blockhash = block.block_hash();
4261                 connect_block(&nodes[0], &block);
4262                 connect_block(&nodes[1], &block);
4263         }
4264
4265         expect_pending_htlcs_forwardable!(nodes[1]);
4266
4267         check_added_monitors!(nodes[1], 1);
4268         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4269         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4270         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4271         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4272         assert!(htlc_timeout_updates.update_fee.is_none());
4273
4274         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4275         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4276         // 100_000 msat as u64, followed by the height at which we failed back above
4277         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4278         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4279         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4280 }
4281
4282 #[test]
4283 fn test_htlc_timeout() {
4284         do_test_htlc_timeout(true);
4285         do_test_htlc_timeout(false);
4286 }
4287
4288 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4289         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4290         let chanmon_cfgs = create_chanmon_cfgs(3);
4291         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4292         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4293         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4294         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4295         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4296
4297         // Make sure all nodes are at the same starting height
4298         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4299         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4300         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4301
4302         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4303         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4304         {
4305                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4306         }
4307         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4308         check_added_monitors!(nodes[1], 1);
4309
4310         // Now attempt to route a second payment, which should be placed in the holding cell
4311         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4312         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4313         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4314         if forwarded_htlc {
4315                 check_added_monitors!(nodes[0], 1);
4316                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4317                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4318                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4319                 expect_pending_htlcs_forwardable!(nodes[1]);
4320         }
4321         check_added_monitors!(nodes[1], 0);
4322
4323         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4324         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4325         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4326         connect_blocks(&nodes[1], 1);
4327
4328         if forwarded_htlc {
4329                 expect_pending_htlcs_forwardable!(nodes[1]);
4330                 check_added_monitors!(nodes[1], 1);
4331                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4332                 assert_eq!(fail_commit.len(), 1);
4333                 match fail_commit[0] {
4334                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4335                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4336                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4337                         },
4338                         _ => unreachable!(),
4339                 }
4340                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4341         } else {
4342                 let events = nodes[1].node.get_and_clear_pending_events();
4343                 assert_eq!(events.len(), 2);
4344                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4345                         assert_eq!(*payment_hash, second_payment_hash);
4346                 } else { panic!("Unexpected event"); }
4347                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4348                         assert_eq!(*payment_hash, second_payment_hash);
4349                 } else { panic!("Unexpected event"); }
4350         }
4351 }
4352
4353 #[test]
4354 fn test_holding_cell_htlc_add_timeouts() {
4355         do_test_holding_cell_htlc_add_timeouts(false);
4356         do_test_holding_cell_htlc_add_timeouts(true);
4357 }
4358
4359 #[test]
4360 fn test_no_txn_manager_serialize_deserialize() {
4361         let chanmon_cfgs = create_chanmon_cfgs(2);
4362         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4363         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4364         let logger: test_utils::TestLogger;
4365         let fee_estimator: test_utils::TestFeeEstimator;
4366         let persister: test_utils::TestPersister;
4367         let new_chain_monitor: test_utils::TestChainMonitor;
4368         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4369         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4370
4371         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4372
4373         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4374
4375         let nodes_0_serialized = nodes[0].node.encode();
4376         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4377         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4378                 .write(&mut chan_0_monitor_serialized).unwrap();
4379
4380         logger = test_utils::TestLogger::new();
4381         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4382         persister = test_utils::TestPersister::new();
4383         let keys_manager = &chanmon_cfgs[0].keys_manager;
4384         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4385         nodes[0].chain_monitor = &new_chain_monitor;
4386         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4387         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4388                 &mut chan_0_monitor_read, keys_manager).unwrap();
4389         assert!(chan_0_monitor_read.is_empty());
4390
4391         let mut nodes_0_read = &nodes_0_serialized[..];
4392         let config = UserConfig::default();
4393         let (_, nodes_0_deserialized_tmp) = {
4394                 let mut channel_monitors = HashMap::new();
4395                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4396                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4397                         default_config: config,
4398                         keys_manager,
4399                         fee_estimator: &fee_estimator,
4400                         chain_monitor: nodes[0].chain_monitor,
4401                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4402                         logger: &logger,
4403                         channel_monitors,
4404                 }).unwrap()
4405         };
4406         nodes_0_deserialized = nodes_0_deserialized_tmp;
4407         assert!(nodes_0_read.is_empty());
4408
4409         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4410         nodes[0].node = &nodes_0_deserialized;
4411         assert_eq!(nodes[0].node.list_channels().len(), 1);
4412         check_added_monitors!(nodes[0], 1);
4413
4414         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4415         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4416         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4417         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4418
4419         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4420         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4421         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4422         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4423
4424         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4425         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4426         for node in nodes.iter() {
4427                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4428                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4429                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4430         }
4431
4432         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4433 }
4434
4435 #[test]
4436 fn test_manager_serialize_deserialize_events() {
4437         // This test makes sure the events field in ChannelManager survives de/serialization
4438         let chanmon_cfgs = create_chanmon_cfgs(2);
4439         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4440         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4441         let fee_estimator: test_utils::TestFeeEstimator;
4442         let persister: test_utils::TestPersister;
4443         let logger: test_utils::TestLogger;
4444         let new_chain_monitor: test_utils::TestChainMonitor;
4445         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4446         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4447
4448         // Start creating a channel, but stop right before broadcasting the funding transaction
4449         let channel_value = 100000;
4450         let push_msat = 10001;
4451         let a_flags = InitFeatures::known();
4452         let b_flags = InitFeatures::known();
4453         let node_a = nodes.remove(0);
4454         let node_b = nodes.remove(0);
4455         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4456         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()));
4457         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()));
4458
4459         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4460
4461         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4462         check_added_monitors!(node_a, 0);
4463
4464         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()));
4465         {
4466                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4467                 assert_eq!(added_monitors.len(), 1);
4468                 assert_eq!(added_monitors[0].0, funding_output);
4469                 added_monitors.clear();
4470         }
4471
4472         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4473         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4474         {
4475                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4476                 assert_eq!(added_monitors.len(), 1);
4477                 assert_eq!(added_monitors[0].0, funding_output);
4478                 added_monitors.clear();
4479         }
4480         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4481
4482         nodes.push(node_a);
4483         nodes.push(node_b);
4484
4485         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4486         let nodes_0_serialized = nodes[0].node.encode();
4487         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4488         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4489
4490         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4491         logger = test_utils::TestLogger::new();
4492         persister = test_utils::TestPersister::new();
4493         let keys_manager = &chanmon_cfgs[0].keys_manager;
4494         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4495         nodes[0].chain_monitor = &new_chain_monitor;
4496         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4497         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4498                 &mut chan_0_monitor_read, keys_manager).unwrap();
4499         assert!(chan_0_monitor_read.is_empty());
4500
4501         let mut nodes_0_read = &nodes_0_serialized[..];
4502         let config = UserConfig::default();
4503         let (_, nodes_0_deserialized_tmp) = {
4504                 let mut channel_monitors = HashMap::new();
4505                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4506                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4507                         default_config: config,
4508                         keys_manager,
4509                         fee_estimator: &fee_estimator,
4510                         chain_monitor: nodes[0].chain_monitor,
4511                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4512                         logger: &logger,
4513                         channel_monitors,
4514                 }).unwrap()
4515         };
4516         nodes_0_deserialized = nodes_0_deserialized_tmp;
4517         assert!(nodes_0_read.is_empty());
4518
4519         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4520
4521         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4522         nodes[0].node = &nodes_0_deserialized;
4523
4524         // After deserializing, make sure the funding_transaction is still held by the channel manager
4525         let events_4 = nodes[0].node.get_and_clear_pending_events();
4526         assert_eq!(events_4.len(), 0);
4527         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4528         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4529
4530         // Make sure the channel is functioning as though the de/serialization never happened
4531         assert_eq!(nodes[0].node.list_channels().len(), 1);
4532         check_added_monitors!(nodes[0], 1);
4533
4534         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4535         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4536         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4537         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4538
4539         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4540         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4541         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4542         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4543
4544         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4545         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4546         for node in nodes.iter() {
4547                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4548                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4549                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4550         }
4551
4552         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4553 }
4554
4555 #[test]
4556 fn test_simple_manager_serialize_deserialize() {
4557         let chanmon_cfgs = create_chanmon_cfgs(2);
4558         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4559         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4560         let logger: test_utils::TestLogger;
4561         let fee_estimator: test_utils::TestFeeEstimator;
4562         let persister: test_utils::TestPersister;
4563         let new_chain_monitor: test_utils::TestChainMonitor;
4564         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4565         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4566         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4567
4568         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4569         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4570
4571         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4572
4573         let nodes_0_serialized = nodes[0].node.encode();
4574         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4575         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4576
4577         logger = test_utils::TestLogger::new();
4578         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4579         persister = test_utils::TestPersister::new();
4580         let keys_manager = &chanmon_cfgs[0].keys_manager;
4581         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4582         nodes[0].chain_monitor = &new_chain_monitor;
4583         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4584         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4585                 &mut chan_0_monitor_read, keys_manager).unwrap();
4586         assert!(chan_0_monitor_read.is_empty());
4587
4588         let mut nodes_0_read = &nodes_0_serialized[..];
4589         let (_, nodes_0_deserialized_tmp) = {
4590                 let mut channel_monitors = HashMap::new();
4591                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4592                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4593                         default_config: UserConfig::default(),
4594                         keys_manager,
4595                         fee_estimator: &fee_estimator,
4596                         chain_monitor: nodes[0].chain_monitor,
4597                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4598                         logger: &logger,
4599                         channel_monitors,
4600                 }).unwrap()
4601         };
4602         nodes_0_deserialized = nodes_0_deserialized_tmp;
4603         assert!(nodes_0_read.is_empty());
4604
4605         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4606         nodes[0].node = &nodes_0_deserialized;
4607         check_added_monitors!(nodes[0], 1);
4608
4609         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4610
4611         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4612         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4613 }
4614
4615 #[test]
4616 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4617         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4618         let chanmon_cfgs = create_chanmon_cfgs(4);
4619         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4620         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4621         let logger: test_utils::TestLogger;
4622         let fee_estimator: test_utils::TestFeeEstimator;
4623         let persister: test_utils::TestPersister;
4624         let new_chain_monitor: test_utils::TestChainMonitor;
4625         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4626         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4627         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4628         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4629         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4630
4631         let mut node_0_stale_monitors_serialized = Vec::new();
4632         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4633                 let mut writer = test_utils::TestVecWriter(Vec::new());
4634                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4635                 node_0_stale_monitors_serialized.push(writer.0);
4636         }
4637
4638         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4639
4640         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4641         let nodes_0_serialized = nodes[0].node.encode();
4642
4643         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4644         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4645         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4646         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4647
4648         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4649         // nodes[3])
4650         let mut node_0_monitors_serialized = Vec::new();
4651         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4652                 let mut writer = test_utils::TestVecWriter(Vec::new());
4653                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4654                 node_0_monitors_serialized.push(writer.0);
4655         }
4656
4657         logger = test_utils::TestLogger::new();
4658         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4659         persister = test_utils::TestPersister::new();
4660         let keys_manager = &chanmon_cfgs[0].keys_manager;
4661         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4662         nodes[0].chain_monitor = &new_chain_monitor;
4663
4664
4665         let mut node_0_stale_monitors = Vec::new();
4666         for serialized in node_0_stale_monitors_serialized.iter() {
4667                 let mut read = &serialized[..];
4668                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4669                 assert!(read.is_empty());
4670                 node_0_stale_monitors.push(monitor);
4671         }
4672
4673         let mut node_0_monitors = Vec::new();
4674         for serialized in node_0_monitors_serialized.iter() {
4675                 let mut read = &serialized[..];
4676                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4677                 assert!(read.is_empty());
4678                 node_0_monitors.push(monitor);
4679         }
4680
4681         let mut nodes_0_read = &nodes_0_serialized[..];
4682         if let Err(msgs::DecodeError::InvalidValue) =
4683                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4684                 default_config: UserConfig::default(),
4685                 keys_manager,
4686                 fee_estimator: &fee_estimator,
4687                 chain_monitor: nodes[0].chain_monitor,
4688                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4689                 logger: &logger,
4690                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4691         }) { } else {
4692                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4693         };
4694
4695         let mut nodes_0_read = &nodes_0_serialized[..];
4696         let (_, nodes_0_deserialized_tmp) =
4697                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4698                 default_config: UserConfig::default(),
4699                 keys_manager,
4700                 fee_estimator: &fee_estimator,
4701                 chain_monitor: nodes[0].chain_monitor,
4702                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4703                 logger: &logger,
4704                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4705         }).unwrap();
4706         nodes_0_deserialized = nodes_0_deserialized_tmp;
4707         assert!(nodes_0_read.is_empty());
4708
4709         { // Channel close should result in a commitment tx
4710                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4711                 assert_eq!(txn.len(), 1);
4712                 check_spends!(txn[0], funding_tx);
4713                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4714         }
4715
4716         for monitor in node_0_monitors.drain(..) {
4717                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4718                 check_added_monitors!(nodes[0], 1);
4719         }
4720         nodes[0].node = &nodes_0_deserialized;
4721         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4722
4723         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4724         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4725         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4726         //... and we can even still claim the payment!
4727         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4728
4729         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4730         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4731         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4732         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4733         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4734         assert_eq!(msg_events.len(), 1);
4735         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4736                 match action {
4737                         &ErrorAction::SendErrorMessage { ref msg } => {
4738                                 assert_eq!(msg.channel_id, channel_id);
4739                         },
4740                         _ => panic!("Unexpected event!"),
4741                 }
4742         }
4743 }
4744
4745 macro_rules! check_spendable_outputs {
4746         ($node: expr, $keysinterface: expr) => {
4747                 {
4748                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4749                         let mut txn = Vec::new();
4750                         let mut all_outputs = Vec::new();
4751                         let secp_ctx = Secp256k1::new();
4752                         for event in events.drain(..) {
4753                                 match event {
4754                                         Event::SpendableOutputs { mut outputs } => {
4755                                                 for outp in outputs.drain(..) {
4756                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4757                                                         all_outputs.push(outp);
4758                                                 }
4759                                         },
4760                                         _ => panic!("Unexpected event"),
4761                                 };
4762                         }
4763                         if all_outputs.len() > 1 {
4764                                 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) {
4765                                         txn.push(tx);
4766                                 }
4767                         }
4768                         txn
4769                 }
4770         }
4771 }
4772
4773 #[test]
4774 fn test_claim_sizeable_push_msat() {
4775         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4776         let chanmon_cfgs = create_chanmon_cfgs(2);
4777         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4778         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4779         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4780
4781         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4782         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4783         check_closed_broadcast!(nodes[1], true);
4784         check_added_monitors!(nodes[1], 1);
4785         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4786         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4787         assert_eq!(node_txn.len(), 1);
4788         check_spends!(node_txn[0], chan.3);
4789         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
4790
4791         mine_transaction(&nodes[1], &node_txn[0]);
4792         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4793
4794         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4795         assert_eq!(spend_txn.len(), 1);
4796         assert_eq!(spend_txn[0].input.len(), 1);
4797         check_spends!(spend_txn[0], node_txn[0]);
4798         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4799 }
4800
4801 #[test]
4802 fn test_claim_on_remote_sizeable_push_msat() {
4803         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4804         // to_remote output is encumbered by a P2WPKH
4805         let chanmon_cfgs = create_chanmon_cfgs(2);
4806         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4807         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4808         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4809
4810         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4811         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4812         check_closed_broadcast!(nodes[0], true);
4813         check_added_monitors!(nodes[0], 1);
4814         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4815
4816         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4817         assert_eq!(node_txn.len(), 1);
4818         check_spends!(node_txn[0], chan.3);
4819         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
4820
4821         mine_transaction(&nodes[1], &node_txn[0]);
4822         check_closed_broadcast!(nodes[1], true);
4823         check_added_monitors!(nodes[1], 1);
4824         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4825         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4826
4827         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4828         assert_eq!(spend_txn.len(), 1);
4829         check_spends!(spend_txn[0], node_txn[0]);
4830 }
4831
4832 #[test]
4833 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4834         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4835         // to_remote output is encumbered by a P2WPKH
4836
4837         let chanmon_cfgs = create_chanmon_cfgs(2);
4838         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4839         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4840         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4841
4842         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4843         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4844         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4845         assert_eq!(revoked_local_txn[0].input.len(), 1);
4846         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4847
4848         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4849         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4850         check_closed_broadcast!(nodes[1], true);
4851         check_added_monitors!(nodes[1], 1);
4852         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4853
4854         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4855         mine_transaction(&nodes[1], &node_txn[0]);
4856         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4857
4858         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4859         assert_eq!(spend_txn.len(), 3);
4860         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4861         check_spends!(spend_txn[1], node_txn[0]);
4862         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4863 }
4864
4865 #[test]
4866 fn test_static_spendable_outputs_preimage_tx() {
4867         let chanmon_cfgs = create_chanmon_cfgs(2);
4868         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4869         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4870         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4871
4872         // Create some initial channels
4873         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4874
4875         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4876
4877         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4878         assert_eq!(commitment_tx[0].input.len(), 1);
4879         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4880
4881         // Settle A's commitment tx on B's chain
4882         nodes[1].node.claim_funds(payment_preimage);
4883         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4884         check_added_monitors!(nodes[1], 1);
4885         mine_transaction(&nodes[1], &commitment_tx[0]);
4886         check_added_monitors!(nodes[1], 1);
4887         let events = nodes[1].node.get_and_clear_pending_msg_events();
4888         match events[0] {
4889                 MessageSendEvent::UpdateHTLCs { .. } => {},
4890                 _ => panic!("Unexpected event"),
4891         }
4892         match events[1] {
4893                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4894                 _ => panic!("Unexepected event"),
4895         }
4896
4897         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4898         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4899         assert_eq!(node_txn.len(), 3);
4900         check_spends!(node_txn[0], commitment_tx[0]);
4901         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4902         check_spends!(node_txn[1], chan_1.3);
4903         check_spends!(node_txn[2], node_txn[1]);
4904
4905         mine_transaction(&nodes[1], &node_txn[0]);
4906         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4907         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4908
4909         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4910         assert_eq!(spend_txn.len(), 1);
4911         check_spends!(spend_txn[0], node_txn[0]);
4912 }
4913
4914 #[test]
4915 fn test_static_spendable_outputs_timeout_tx() {
4916         let chanmon_cfgs = create_chanmon_cfgs(2);
4917         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4918         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4919         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4920
4921         // Create some initial channels
4922         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4923
4924         // Rebalance the network a bit by relaying one payment through all the channels ...
4925         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4926
4927         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4928
4929         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4930         assert_eq!(commitment_tx[0].input.len(), 1);
4931         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4932
4933         // Settle A's commitment tx on B' chain
4934         mine_transaction(&nodes[1], &commitment_tx[0]);
4935         check_added_monitors!(nodes[1], 1);
4936         let events = nodes[1].node.get_and_clear_pending_msg_events();
4937         match events[0] {
4938                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4939                 _ => panic!("Unexpected event"),
4940         }
4941         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4942
4943         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4944         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4945         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4946         check_spends!(node_txn[0], chan_1.3.clone());
4947         check_spends!(node_txn[1],  commitment_tx[0].clone());
4948         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4949
4950         mine_transaction(&nodes[1], &node_txn[1]);
4951         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4952         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4953         expect_payment_failed!(nodes[1], our_payment_hash, true);
4954
4955         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4956         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4957         check_spends!(spend_txn[0], commitment_tx[0]);
4958         check_spends!(spend_txn[1], node_txn[1]);
4959         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4960 }
4961
4962 #[test]
4963 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4964         let chanmon_cfgs = create_chanmon_cfgs(2);
4965         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4966         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4967         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4968
4969         // Create some initial channels
4970         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4971
4972         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4973         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4974         assert_eq!(revoked_local_txn[0].input.len(), 1);
4975         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4976
4977         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4978
4979         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4980         check_closed_broadcast!(nodes[1], true);
4981         check_added_monitors!(nodes[1], 1);
4982         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4983
4984         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4985         assert_eq!(node_txn.len(), 2);
4986         assert_eq!(node_txn[0].input.len(), 2);
4987         check_spends!(node_txn[0], revoked_local_txn[0]);
4988
4989         mine_transaction(&nodes[1], &node_txn[0]);
4990         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4991
4992         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4993         assert_eq!(spend_txn.len(), 1);
4994         check_spends!(spend_txn[0], node_txn[0]);
4995 }
4996
4997 #[test]
4998 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4999         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5000         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5001         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5002         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5003         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5004
5005         // Create some initial channels
5006         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5007
5008         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5009         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5010         assert_eq!(revoked_local_txn[0].input.len(), 1);
5011         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5012
5013         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5014
5015         // A will generate HTLC-Timeout from revoked commitment tx
5016         mine_transaction(&nodes[0], &revoked_local_txn[0]);
5017         check_closed_broadcast!(nodes[0], true);
5018         check_added_monitors!(nodes[0], 1);
5019         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5020         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5021
5022         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5023         assert_eq!(revoked_htlc_txn.len(), 2);
5024         check_spends!(revoked_htlc_txn[0], chan_1.3);
5025         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5026         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5027         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5028         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5029
5030         // B will generate justice tx from A's revoked commitment/HTLC tx
5031         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5032         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5033         check_closed_broadcast!(nodes[1], true);
5034         check_added_monitors!(nodes[1], 1);
5035         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5036
5037         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5038         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5039         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5040         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5041         // transactions next...
5042         assert_eq!(node_txn[0].input.len(), 3);
5043         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5044
5045         assert_eq!(node_txn[1].input.len(), 2);
5046         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5047         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5048                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5049         } else {
5050                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5051                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5052         }
5053
5054         assert_eq!(node_txn[2].input.len(), 1);
5055         check_spends!(node_txn[2], chan_1.3);
5056
5057         mine_transaction(&nodes[1], &node_txn[1]);
5058         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5059
5060         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5061         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5062         assert_eq!(spend_txn.len(), 1);
5063         assert_eq!(spend_txn[0].input.len(), 1);
5064         check_spends!(spend_txn[0], node_txn[1]);
5065 }
5066
5067 #[test]
5068 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5069         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5070         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5071         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5072         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5073         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5074
5075         // Create some initial channels
5076         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5077
5078         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5079         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5080         assert_eq!(revoked_local_txn[0].input.len(), 1);
5081         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5082
5083         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5084         assert_eq!(revoked_local_txn[0].output.len(), 2);
5085
5086         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5087
5088         // B will generate HTLC-Success from revoked commitment tx
5089         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5090         check_closed_broadcast!(nodes[1], true);
5091         check_added_monitors!(nodes[1], 1);
5092         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5093         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5094
5095         assert_eq!(revoked_htlc_txn.len(), 2);
5096         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5097         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5098         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5099
5100         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5101         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5102         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5103
5104         // A will generate justice tx from B's revoked commitment/HTLC tx
5105         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5106         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5107         check_closed_broadcast!(nodes[0], true);
5108         check_added_monitors!(nodes[0], 1);
5109         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5110
5111         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5112         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5113
5114         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5115         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5116         // transactions next...
5117         assert_eq!(node_txn[0].input.len(), 2);
5118         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5119         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5120                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5121         } else {
5122                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5123                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5124         }
5125
5126         assert_eq!(node_txn[1].input.len(), 1);
5127         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5128
5129         check_spends!(node_txn[2], chan_1.3);
5130
5131         mine_transaction(&nodes[0], &node_txn[1]);
5132         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5133
5134         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5135         // didn't try to generate any new transactions.
5136
5137         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5138         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5139         assert_eq!(spend_txn.len(), 3);
5140         assert_eq!(spend_txn[0].input.len(), 1);
5141         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5142         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5143         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5144         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5145 }
5146
5147 #[test]
5148 fn test_onchain_to_onchain_claim() {
5149         // Test that in case of channel closure, we detect the state of output and claim HTLC
5150         // on downstream peer's remote commitment tx.
5151         // First, have C claim an HTLC against its own latest commitment transaction.
5152         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5153         // channel.
5154         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5155         // gets broadcast.
5156
5157         let chanmon_cfgs = create_chanmon_cfgs(3);
5158         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5159         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5160         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5161
5162         // Create some initial channels
5163         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5164         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5165
5166         // Ensure all nodes are at the same height
5167         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5168         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5169         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5170         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5171
5172         // Rebalance the network a bit by relaying one payment through all the channels ...
5173         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5174         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5175
5176         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5177         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5178         check_spends!(commitment_tx[0], chan_2.3);
5179         nodes[2].node.claim_funds(payment_preimage);
5180         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5181         check_added_monitors!(nodes[2], 1);
5182         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5183         assert!(updates.update_add_htlcs.is_empty());
5184         assert!(updates.update_fail_htlcs.is_empty());
5185         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5186         assert!(updates.update_fail_malformed_htlcs.is_empty());
5187
5188         mine_transaction(&nodes[2], &commitment_tx[0]);
5189         check_closed_broadcast!(nodes[2], true);
5190         check_added_monitors!(nodes[2], 1);
5191         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5192
5193         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5194         assert_eq!(c_txn.len(), 3);
5195         assert_eq!(c_txn[0], c_txn[2]);
5196         assert_eq!(commitment_tx[0], c_txn[1]);
5197         check_spends!(c_txn[1], chan_2.3);
5198         check_spends!(c_txn[2], c_txn[1]);
5199         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5200         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5201         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5202         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5203
5204         // 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
5205         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5206         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5207         check_added_monitors!(nodes[1], 1);
5208         let events = nodes[1].node.get_and_clear_pending_events();
5209         assert_eq!(events.len(), 2);
5210         match events[0] {
5211                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5212                 _ => panic!("Unexpected event"),
5213         }
5214         match events[1] {
5215                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5216                         assert_eq!(fee_earned_msat, Some(1000));
5217                         assert_eq!(prev_channel_id, Some(chan_1.2));
5218                         assert_eq!(claim_from_onchain_tx, true);
5219                         assert_eq!(next_channel_id, Some(chan_2.2));
5220                 },
5221                 _ => panic!("Unexpected event"),
5222         }
5223         {
5224                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5225                 // ChannelMonitor: claim tx
5226                 assert_eq!(b_txn.len(), 1);
5227                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5228                 b_txn.clear();
5229         }
5230         check_added_monitors!(nodes[1], 1);
5231         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5232         assert_eq!(msg_events.len(), 3);
5233         match msg_events[0] {
5234                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5235                 _ => panic!("Unexpected event"),
5236         }
5237         match msg_events[1] {
5238                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5239                 _ => panic!("Unexpected event"),
5240         }
5241         match msg_events[2] {
5242                 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, .. } } => {
5243                         assert!(update_add_htlcs.is_empty());
5244                         assert!(update_fail_htlcs.is_empty());
5245                         assert_eq!(update_fulfill_htlcs.len(), 1);
5246                         assert!(update_fail_malformed_htlcs.is_empty());
5247                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5248                 },
5249                 _ => panic!("Unexpected event"),
5250         };
5251         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5252         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5253         mine_transaction(&nodes[1], &commitment_tx[0]);
5254         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5255         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5256         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5257         assert_eq!(b_txn.len(), 3);
5258         check_spends!(b_txn[1], chan_1.3);
5259         check_spends!(b_txn[2], b_txn[1]);
5260         check_spends!(b_txn[0], commitment_tx[0]);
5261         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5262         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5263         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5264
5265         check_closed_broadcast!(nodes[1], true);
5266         check_added_monitors!(nodes[1], 1);
5267 }
5268
5269 #[test]
5270 fn test_duplicate_payment_hash_one_failure_one_success() {
5271         // Topology : A --> B --> C --> D
5272         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5273         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5274         // we forward one of the payments onwards to D.
5275         let chanmon_cfgs = create_chanmon_cfgs(4);
5276         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5277         // When this test was written, the default base fee floated based on the HTLC count.
5278         // It is now fixed, so we simply set the fee to the expected value here.
5279         let mut config = test_default_channel_config();
5280         config.channel_config.forwarding_fee_base_msat = 196;
5281         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5282                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5283         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5284
5285         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5286         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5287         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5288
5289         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5290         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5291         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5292         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5293         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5294
5295         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5296
5297         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5298         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5299         // script push size limit so that the below script length checks match
5300         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5301         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5302                 .with_features(InvoiceFeatures::known());
5303         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5304         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5305
5306         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5307         assert_eq!(commitment_txn[0].input.len(), 1);
5308         check_spends!(commitment_txn[0], chan_2.3);
5309
5310         mine_transaction(&nodes[1], &commitment_txn[0]);
5311         check_closed_broadcast!(nodes[1], true);
5312         check_added_monitors!(nodes[1], 1);
5313         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5314         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5315
5316         let htlc_timeout_tx;
5317         { // Extract one of the two HTLC-Timeout transaction
5318                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5319                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5320                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5321                 check_spends!(node_txn[0], chan_2.3);
5322
5323                 check_spends!(node_txn[1], commitment_txn[0]);
5324                 assert_eq!(node_txn[1].input.len(), 1);
5325
5326                 if node_txn.len() > 3 {
5327                         check_spends!(node_txn[2], commitment_txn[0]);
5328                         assert_eq!(node_txn[2].input.len(), 1);
5329                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5330
5331                         check_spends!(node_txn[3], commitment_txn[0]);
5332                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5333                 } else {
5334                         check_spends!(node_txn[2], commitment_txn[0]);
5335                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5336                 }
5337
5338                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5339                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5340                 if node_txn.len() > 3 {
5341                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5342                 }
5343                 htlc_timeout_tx = node_txn[1].clone();
5344         }
5345
5346         nodes[2].node.claim_funds(our_payment_preimage);
5347         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5348
5349         mine_transaction(&nodes[2], &commitment_txn[0]);
5350         check_added_monitors!(nodes[2], 2);
5351         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5352         let events = nodes[2].node.get_and_clear_pending_msg_events();
5353         match events[0] {
5354                 MessageSendEvent::UpdateHTLCs { .. } => {},
5355                 _ => panic!("Unexpected event"),
5356         }
5357         match events[1] {
5358                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5359                 _ => panic!("Unexepected event"),
5360         }
5361         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5362         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)
5363         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5364         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5365         assert_eq!(htlc_success_txn[0].input.len(), 1);
5366         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5367         assert_eq!(htlc_success_txn[1].input.len(), 1);
5368         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5369         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5370         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5371         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5372         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5373         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5374
5375         mine_transaction(&nodes[1], &htlc_timeout_tx);
5376         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5377         expect_pending_htlcs_forwardable!(nodes[1]);
5378         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5379         assert!(htlc_updates.update_add_htlcs.is_empty());
5380         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5381         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5382         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5383         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5384         check_added_monitors!(nodes[1], 1);
5385
5386         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5387         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5388         {
5389                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5390         }
5391         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5392
5393         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5394         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5395         // and nodes[2] fee) is rounded down and then claimed in full.
5396         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5397         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5398         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5399         assert!(updates.update_add_htlcs.is_empty());
5400         assert!(updates.update_fail_htlcs.is_empty());
5401         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5402         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5403         assert!(updates.update_fail_malformed_htlcs.is_empty());
5404         check_added_monitors!(nodes[1], 1);
5405
5406         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5407         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5408
5409         let events = nodes[0].node.get_and_clear_pending_events();
5410         match events[0] {
5411                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5412                         assert_eq!(*payment_preimage, our_payment_preimage);
5413                         assert_eq!(*payment_hash, duplicate_payment_hash);
5414                 }
5415                 _ => panic!("Unexpected event"),
5416         }
5417 }
5418
5419 #[test]
5420 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5421         let chanmon_cfgs = create_chanmon_cfgs(2);
5422         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5423         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5424         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5425
5426         // Create some initial channels
5427         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5428
5429         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5430         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5431         assert_eq!(local_txn.len(), 1);
5432         assert_eq!(local_txn[0].input.len(), 1);
5433         check_spends!(local_txn[0], chan_1.3);
5434
5435         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5436         nodes[1].node.claim_funds(payment_preimage);
5437         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5438         check_added_monitors!(nodes[1], 1);
5439
5440         mine_transaction(&nodes[1], &local_txn[0]);
5441         check_added_monitors!(nodes[1], 1);
5442         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5443         let events = nodes[1].node.get_and_clear_pending_msg_events();
5444         match events[0] {
5445                 MessageSendEvent::UpdateHTLCs { .. } => {},
5446                 _ => panic!("Unexpected event"),
5447         }
5448         match events[1] {
5449                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5450                 _ => panic!("Unexepected event"),
5451         }
5452         let node_tx = {
5453                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5454                 assert_eq!(node_txn.len(), 3);
5455                 assert_eq!(node_txn[0], node_txn[2]);
5456                 assert_eq!(node_txn[1], local_txn[0]);
5457                 assert_eq!(node_txn[0].input.len(), 1);
5458                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5459                 check_spends!(node_txn[0], local_txn[0]);
5460                 node_txn[0].clone()
5461         };
5462
5463         mine_transaction(&nodes[1], &node_tx);
5464         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5465
5466         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5467         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5468         assert_eq!(spend_txn.len(), 1);
5469         assert_eq!(spend_txn[0].input.len(), 1);
5470         check_spends!(spend_txn[0], node_tx);
5471         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5472 }
5473
5474 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5475         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5476         // unrevoked commitment transaction.
5477         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5478         // a remote RAA before they could be failed backwards (and combinations thereof).
5479         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5480         // use the same payment hashes.
5481         // Thus, we use a six-node network:
5482         //
5483         // A \         / E
5484         //    - C - D -
5485         // B /         \ F
5486         // And test where C fails back to A/B when D announces its latest commitment transaction
5487         let chanmon_cfgs = create_chanmon_cfgs(6);
5488         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5489         // When this test was written, the default base fee floated based on the HTLC count.
5490         // It is now fixed, so we simply set the fee to the expected value here.
5491         let mut config = test_default_channel_config();
5492         config.channel_config.forwarding_fee_base_msat = 196;
5493         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5494                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5495         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5496
5497         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5498         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5499         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5500         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5501         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5502
5503         // Rebalance and check output sanity...
5504         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5505         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5506         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5507
5508         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5509         // 0th HTLC:
5510         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
5511         // 1st HTLC:
5512         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
5513         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5514         // 2nd HTLC:
5515         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
5516         // 3rd HTLC:
5517         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
5518         // 4th HTLC:
5519         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5520         // 5th HTLC:
5521         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5522         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5523         // 6th HTLC:
5524         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());
5525         // 7th HTLC:
5526         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());
5527
5528         // 8th HTLC:
5529         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5530         // 9th HTLC:
5531         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5532         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
5533
5534         // 10th HTLC:
5535         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
5536         // 11th HTLC:
5537         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5538         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());
5539
5540         // Double-check that six of the new HTLC were added
5541         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5542         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5543         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5544         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5545
5546         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5547         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5548         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5549         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5550         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5551         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5552         check_added_monitors!(nodes[4], 0);
5553         expect_pending_htlcs_forwardable!(nodes[4]);
5554         check_added_monitors!(nodes[4], 1);
5555
5556         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5557         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5558         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5559         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5560         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5561         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5562
5563         // Fail 3rd below-dust and 7th above-dust HTLCs
5564         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5565         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5566         check_added_monitors!(nodes[5], 0);
5567         expect_pending_htlcs_forwardable!(nodes[5]);
5568         check_added_monitors!(nodes[5], 1);
5569
5570         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5571         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5572         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5573         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5574
5575         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5576
5577         expect_pending_htlcs_forwardable!(nodes[3]);
5578         check_added_monitors!(nodes[3], 1);
5579         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5580         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5581         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5582         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5583         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5584         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5585         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5586         if deliver_last_raa {
5587                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5588         } else {
5589                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5590         }
5591
5592         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5593         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5594         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5595         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5596         //
5597         // We now broadcast the latest commitment transaction, which *should* result in failures for
5598         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5599         // the non-broadcast above-dust HTLCs.
5600         //
5601         // Alternatively, we may broadcast the previous commitment transaction, which should only
5602         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5603         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5604
5605         if announce_latest {
5606                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5607         } else {
5608                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5609         }
5610         let events = nodes[2].node.get_and_clear_pending_events();
5611         let close_event = if deliver_last_raa {
5612                 assert_eq!(events.len(), 2);
5613                 events[1].clone()
5614         } else {
5615                 assert_eq!(events.len(), 1);
5616                 events[0].clone()
5617         };
5618         match close_event {
5619                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5620                 _ => panic!("Unexpected event"),
5621         }
5622
5623         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5624         check_closed_broadcast!(nodes[2], true);
5625         if deliver_last_raa {
5626                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5627         } else {
5628                 expect_pending_htlcs_forwardable!(nodes[2]);
5629         }
5630         check_added_monitors!(nodes[2], 3);
5631
5632         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5633         assert_eq!(cs_msgs.len(), 2);
5634         let mut a_done = false;
5635         for msg in cs_msgs {
5636                 match msg {
5637                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5638                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5639                                 // should be failed-backwards here.
5640                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5641                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5642                                         for htlc in &updates.update_fail_htlcs {
5643                                                 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 });
5644                                         }
5645                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5646                                         assert!(!a_done);
5647                                         a_done = true;
5648                                         &nodes[0]
5649                                 } else {
5650                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5651                                         for htlc in &updates.update_fail_htlcs {
5652                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5653                                         }
5654                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5655                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5656                                         &nodes[1]
5657                                 };
5658                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5659                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5660                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5661                                 if announce_latest {
5662                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5663                                         if *node_id == nodes[0].node.get_our_node_id() {
5664                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5665                                         }
5666                                 }
5667                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5668                         },
5669                         _ => panic!("Unexpected event"),
5670                 }
5671         }
5672
5673         let as_events = nodes[0].node.get_and_clear_pending_events();
5674         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5675         let mut as_failds = HashSet::new();
5676         let mut as_updates = 0;
5677         for event in as_events.iter() {
5678                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5679                         assert!(as_failds.insert(*payment_hash));
5680                         if *payment_hash != payment_hash_2 {
5681                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5682                         } else {
5683                                 assert!(!rejected_by_dest);
5684                         }
5685                         if network_update.is_some() {
5686                                 as_updates += 1;
5687                         }
5688                 } else { panic!("Unexpected event"); }
5689         }
5690         assert!(as_failds.contains(&payment_hash_1));
5691         assert!(as_failds.contains(&payment_hash_2));
5692         if announce_latest {
5693                 assert!(as_failds.contains(&payment_hash_3));
5694                 assert!(as_failds.contains(&payment_hash_5));
5695         }
5696         assert!(as_failds.contains(&payment_hash_6));
5697
5698         let bs_events = nodes[1].node.get_and_clear_pending_events();
5699         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5700         let mut bs_failds = HashSet::new();
5701         let mut bs_updates = 0;
5702         for event in bs_events.iter() {
5703                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5704                         assert!(bs_failds.insert(*payment_hash));
5705                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5706                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5707                         } else {
5708                                 assert!(!rejected_by_dest);
5709                         }
5710                         if network_update.is_some() {
5711                                 bs_updates += 1;
5712                         }
5713                 } else { panic!("Unexpected event"); }
5714         }
5715         assert!(bs_failds.contains(&payment_hash_1));
5716         assert!(bs_failds.contains(&payment_hash_2));
5717         if announce_latest {
5718                 assert!(bs_failds.contains(&payment_hash_4));
5719         }
5720         assert!(bs_failds.contains(&payment_hash_5));
5721
5722         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5723         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5724         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5725         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5726         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5727         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5728 }
5729
5730 #[test]
5731 fn test_fail_backwards_latest_remote_announce_a() {
5732         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5733 }
5734
5735 #[test]
5736 fn test_fail_backwards_latest_remote_announce_b() {
5737         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5738 }
5739
5740 #[test]
5741 fn test_fail_backwards_previous_remote_announce() {
5742         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5743         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5744         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5745 }
5746
5747 #[test]
5748 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5749         let chanmon_cfgs = create_chanmon_cfgs(2);
5750         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5751         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5752         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5753
5754         // Create some initial channels
5755         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5756
5757         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5758         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5759         assert_eq!(local_txn[0].input.len(), 1);
5760         check_spends!(local_txn[0], chan_1.3);
5761
5762         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5763         mine_transaction(&nodes[0], &local_txn[0]);
5764         check_closed_broadcast!(nodes[0], true);
5765         check_added_monitors!(nodes[0], 1);
5766         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5767         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5768
5769         let htlc_timeout = {
5770                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5771                 assert_eq!(node_txn.len(), 2);
5772                 check_spends!(node_txn[0], chan_1.3);
5773                 assert_eq!(node_txn[1].input.len(), 1);
5774                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5775                 check_spends!(node_txn[1], local_txn[0]);
5776                 node_txn[1].clone()
5777         };
5778
5779         mine_transaction(&nodes[0], &htlc_timeout);
5780         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5781         expect_payment_failed!(nodes[0], our_payment_hash, true);
5782
5783         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5784         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5785         assert_eq!(spend_txn.len(), 3);
5786         check_spends!(spend_txn[0], local_txn[0]);
5787         assert_eq!(spend_txn[1].input.len(), 1);
5788         check_spends!(spend_txn[1], htlc_timeout);
5789         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5790         assert_eq!(spend_txn[2].input.len(), 2);
5791         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5792         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5793                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5794 }
5795
5796 #[test]
5797 fn test_key_derivation_params() {
5798         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5799         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5800         // let us re-derive the channel key set to then derive a delayed_payment_key.
5801
5802         let chanmon_cfgs = create_chanmon_cfgs(3);
5803
5804         // We manually create the node configuration to backup the seed.
5805         let seed = [42; 32];
5806         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5807         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);
5808         let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5809         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() };
5810         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5811         node_cfgs.remove(0);
5812         node_cfgs.insert(0, node);
5813
5814         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5815         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5816
5817         // Create some initial channels
5818         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5819         // for node 0
5820         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5821         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5822         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5823
5824         // Ensure all nodes are at the same height
5825         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5826         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5827         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5828         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5829
5830         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5831         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5832         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5833         assert_eq!(local_txn_1[0].input.len(), 1);
5834         check_spends!(local_txn_1[0], chan_1.3);
5835
5836         // We check funding pubkey are unique
5837         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]));
5838         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]));
5839         if from_0_funding_key_0 == from_1_funding_key_0
5840             || from_0_funding_key_0 == from_1_funding_key_1
5841             || from_0_funding_key_1 == from_1_funding_key_0
5842             || from_0_funding_key_1 == from_1_funding_key_1 {
5843                 panic!("Funding pubkeys aren't unique");
5844         }
5845
5846         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5847         mine_transaction(&nodes[0], &local_txn_1[0]);
5848         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5849         check_closed_broadcast!(nodes[0], true);
5850         check_added_monitors!(nodes[0], 1);
5851         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5852
5853         let htlc_timeout = {
5854                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5855                 assert_eq!(node_txn[1].input.len(), 1);
5856                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5857                 check_spends!(node_txn[1], local_txn_1[0]);
5858                 node_txn[1].clone()
5859         };
5860
5861         mine_transaction(&nodes[0], &htlc_timeout);
5862         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5863         expect_payment_failed!(nodes[0], our_payment_hash, true);
5864
5865         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5866         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5867         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5868         assert_eq!(spend_txn.len(), 3);
5869         check_spends!(spend_txn[0], local_txn_1[0]);
5870         assert_eq!(spend_txn[1].input.len(), 1);
5871         check_spends!(spend_txn[1], htlc_timeout);
5872         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5873         assert_eq!(spend_txn[2].input.len(), 2);
5874         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5875         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5876                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5877 }
5878
5879 #[test]
5880 fn test_static_output_closing_tx() {
5881         let chanmon_cfgs = create_chanmon_cfgs(2);
5882         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5883         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5884         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5885
5886         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5887
5888         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5889         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5890
5891         mine_transaction(&nodes[0], &closing_tx);
5892         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5893         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5894
5895         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5896         assert_eq!(spend_txn.len(), 1);
5897         check_spends!(spend_txn[0], closing_tx);
5898
5899         mine_transaction(&nodes[1], &closing_tx);
5900         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5901         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5902
5903         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5904         assert_eq!(spend_txn.len(), 1);
5905         check_spends!(spend_txn[0], closing_tx);
5906 }
5907
5908 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5909         let chanmon_cfgs = create_chanmon_cfgs(2);
5910         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5911         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5912         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5913         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5914
5915         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5916
5917         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5918         // present in B's local commitment transaction, but none of A's commitment transactions.
5919         nodes[1].node.claim_funds(payment_preimage);
5920         check_added_monitors!(nodes[1], 1);
5921         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5922
5923         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5924         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5925         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5926
5927         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5928         check_added_monitors!(nodes[0], 1);
5929         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5930         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5931         check_added_monitors!(nodes[1], 1);
5932
5933         let starting_block = nodes[1].best_block_info();
5934         let mut block = Block {
5935                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5936                 txdata: vec![],
5937         };
5938         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5939                 connect_block(&nodes[1], &block);
5940                 block.header.prev_blockhash = block.block_hash();
5941         }
5942         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5943         check_closed_broadcast!(nodes[1], true);
5944         check_added_monitors!(nodes[1], 1);
5945         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5946 }
5947
5948 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5949         let chanmon_cfgs = create_chanmon_cfgs(2);
5950         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5951         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5952         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5953         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5954
5955         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5956         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5957         check_added_monitors!(nodes[0], 1);
5958
5959         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5960
5961         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5962         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5963         // to "time out" the HTLC.
5964
5965         let starting_block = nodes[1].best_block_info();
5966         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5967
5968         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5969                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5970                 header.prev_blockhash = header.block_hash();
5971         }
5972         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5973         check_closed_broadcast!(nodes[0], true);
5974         check_added_monitors!(nodes[0], 1);
5975         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5976 }
5977
5978 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5979         let chanmon_cfgs = create_chanmon_cfgs(3);
5980         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5981         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5982         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5983         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5984
5985         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5986         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5987         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5988         // actually revoked.
5989         let htlc_value = if use_dust { 50000 } else { 3000000 };
5990         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5991         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5992         expect_pending_htlcs_forwardable!(nodes[1]);
5993         check_added_monitors!(nodes[1], 1);
5994
5995         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5996         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5997         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5998         check_added_monitors!(nodes[0], 1);
5999         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6000         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6001         check_added_monitors!(nodes[1], 1);
6002         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6003         check_added_monitors!(nodes[1], 1);
6004         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6005
6006         if check_revoke_no_close {
6007                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6008                 check_added_monitors!(nodes[0], 1);
6009         }
6010
6011         let starting_block = nodes[1].best_block_info();
6012         let mut block = Block {
6013                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6014                 txdata: vec![],
6015         };
6016         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6017                 connect_block(&nodes[0], &block);
6018                 block.header.prev_blockhash = block.block_hash();
6019         }
6020         if !check_revoke_no_close {
6021                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6022                 check_closed_broadcast!(nodes[0], true);
6023                 check_added_monitors!(nodes[0], 1);
6024                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6025         } else {
6026                 let events = nodes[0].node.get_and_clear_pending_events();
6027                 assert_eq!(events.len(), 2);
6028                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6029                         assert_eq!(*payment_hash, our_payment_hash);
6030                 } else { panic!("Unexpected event"); }
6031                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6032                         assert_eq!(*payment_hash, our_payment_hash);
6033                 } else { panic!("Unexpected event"); }
6034         }
6035 }
6036
6037 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6038 // There are only a few cases to test here:
6039 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
6040 //    broadcastable commitment transactions result in channel closure,
6041 //  * its included in an unrevoked-but-previous remote commitment transaction,
6042 //  * its included in the latest remote or local commitment transactions.
6043 // We test each of the three possible commitment transactions individually and use both dust and
6044 // non-dust HTLCs.
6045 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6046 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6047 // tested for at least one of the cases in other tests.
6048 #[test]
6049 fn htlc_claim_single_commitment_only_a() {
6050         do_htlc_claim_local_commitment_only(true);
6051         do_htlc_claim_local_commitment_only(false);
6052
6053         do_htlc_claim_current_remote_commitment_only(true);
6054         do_htlc_claim_current_remote_commitment_only(false);
6055 }
6056
6057 #[test]
6058 fn htlc_claim_single_commitment_only_b() {
6059         do_htlc_claim_previous_remote_commitment_only(true, false);
6060         do_htlc_claim_previous_remote_commitment_only(false, false);
6061         do_htlc_claim_previous_remote_commitment_only(true, true);
6062         do_htlc_claim_previous_remote_commitment_only(false, true);
6063 }
6064
6065 #[test]
6066 #[should_panic]
6067 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6068         let chanmon_cfgs = create_chanmon_cfgs(2);
6069         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6070         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6071         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6072         // Force duplicate randomness for every get-random call
6073         for node in nodes.iter() {
6074                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6075         }
6076
6077         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6078         let channel_value_satoshis=10000;
6079         let push_msat=10001;
6080         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6081         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6082         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6083         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6084
6085         // Create a second channel with the same random values. This used to panic due to a colliding
6086         // channel_id, but now panics due to a colliding outbound SCID alias.
6087         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6088 }
6089
6090 #[test]
6091 fn bolt2_open_channel_sending_node_checks_part2() {
6092         let chanmon_cfgs = create_chanmon_cfgs(2);
6093         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6094         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6095         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6096
6097         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6098         let channel_value_satoshis=2^24;
6099         let push_msat=10001;
6100         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6101
6102         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6103         let channel_value_satoshis=10000;
6104         // Test when push_msat is equal to 1000 * funding_satoshis.
6105         let push_msat=1000*channel_value_satoshis+1;
6106         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6107
6108         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6109         let channel_value_satoshis=10000;
6110         let push_msat=10001;
6111         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
6112         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6113         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6114
6115         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6116         // 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
6117         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6118
6119         // 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.
6120         assert!(BREAKDOWN_TIMEOUT>0);
6121         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6122
6123         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6124         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6125         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6126
6127         // 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.
6128         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6129         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6130         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6131         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6132         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6133 }
6134
6135 #[test]
6136 fn bolt2_open_channel_sane_dust_limit() {
6137         let chanmon_cfgs = create_chanmon_cfgs(2);
6138         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6139         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6140         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6141
6142         let channel_value_satoshis=1000000;
6143         let push_msat=10001;
6144         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6145         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6146         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6147         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6148
6149         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6150         let events = nodes[1].node.get_and_clear_pending_msg_events();
6151         let err_msg = match events[0] {
6152                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6153                         msg.clone()
6154                 },
6155                 _ => panic!("Unexpected event"),
6156         };
6157         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6158 }
6159
6160 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6161 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6162 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6163 // is no longer affordable once it's freed.
6164 #[test]
6165 fn test_fail_holding_cell_htlc_upon_free() {
6166         let chanmon_cfgs = create_chanmon_cfgs(2);
6167         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6168         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6169         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6170         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6171
6172         // First nodes[0] generates an update_fee, setting the channel's
6173         // pending_update_fee.
6174         {
6175                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6176                 *feerate_lock += 20;
6177         }
6178         nodes[0].node.timer_tick_occurred();
6179         check_added_monitors!(nodes[0], 1);
6180
6181         let events = nodes[0].node.get_and_clear_pending_msg_events();
6182         assert_eq!(events.len(), 1);
6183         let (update_msg, commitment_signed) = match events[0] {
6184                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6185                         (update_fee.as_ref(), commitment_signed)
6186                 },
6187                 _ => panic!("Unexpected event"),
6188         };
6189
6190         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6191
6192         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6193         let channel_reserve = chan_stat.channel_reserve_msat;
6194         let feerate = get_feerate!(nodes[0], chan.2);
6195         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6196
6197         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6198         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6199         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6200
6201         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6202         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6203         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6204         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6205
6206         // Flush the pending fee update.
6207         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6208         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6209         check_added_monitors!(nodes[1], 1);
6210         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6211         check_added_monitors!(nodes[0], 1);
6212
6213         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6214         // HTLC, but now that the fee has been raised the payment will now fail, causing
6215         // us to surface its failure to the user.
6216         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6217         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6218         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);
6219         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 {}",
6220                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6221         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6222
6223         // Check that the payment failed to be sent out.
6224         let events = nodes[0].node.get_and_clear_pending_events();
6225         assert_eq!(events.len(), 1);
6226         match &events[0] {
6227                 &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, .. } => {
6228                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6229                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6230                         assert_eq!(*rejected_by_dest, false);
6231                         assert_eq!(*all_paths_failed, true);
6232                         assert_eq!(*network_update, None);
6233                         assert_eq!(*short_channel_id, None);
6234                         assert_eq!(*error_code, None);
6235                         assert_eq!(*error_data, None);
6236                 },
6237                 _ => panic!("Unexpected event"),
6238         }
6239 }
6240
6241 // Test that if multiple HTLCs are released from the holding cell and one is
6242 // valid but the other is no longer valid upon release, the valid HTLC can be
6243 // successfully completed while the other one fails as expected.
6244 #[test]
6245 fn test_free_and_fail_holding_cell_htlcs() {
6246         let chanmon_cfgs = create_chanmon_cfgs(2);
6247         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6248         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6249         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6250         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6251
6252         // First nodes[0] generates an update_fee, setting the channel's
6253         // pending_update_fee.
6254         {
6255                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6256                 *feerate_lock += 200;
6257         }
6258         nodes[0].node.timer_tick_occurred();
6259         check_added_monitors!(nodes[0], 1);
6260
6261         let events = nodes[0].node.get_and_clear_pending_msg_events();
6262         assert_eq!(events.len(), 1);
6263         let (update_msg, commitment_signed) = match events[0] {
6264                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6265                         (update_fee.as_ref(), commitment_signed)
6266                 },
6267                 _ => panic!("Unexpected event"),
6268         };
6269
6270         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6271
6272         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6273         let channel_reserve = chan_stat.channel_reserve_msat;
6274         let feerate = get_feerate!(nodes[0], chan.2);
6275         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6276
6277         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6278         let amt_1 = 20000;
6279         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6280         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6281         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6282
6283         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6284         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6285         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6286         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6287         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6288         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6289         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6290
6291         // Flush the pending fee update.
6292         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6293         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6294         check_added_monitors!(nodes[1], 1);
6295         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6296         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6297         check_added_monitors!(nodes[0], 2);
6298
6299         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6300         // but now that the fee has been raised the second payment will now fail, causing us
6301         // to surface its failure to the user. The first payment should succeed.
6302         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6303         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6304         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);
6305         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 {}",
6306                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6307         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6308
6309         // Check that the second payment failed to be sent out.
6310         let events = nodes[0].node.get_and_clear_pending_events();
6311         assert_eq!(events.len(), 1);
6312         match &events[0] {
6313                 &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, .. } => {
6314                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6315                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6316                         assert_eq!(*rejected_by_dest, false);
6317                         assert_eq!(*all_paths_failed, true);
6318                         assert_eq!(*network_update, None);
6319                         assert_eq!(*short_channel_id, None);
6320                         assert_eq!(*error_code, None);
6321                         assert_eq!(*error_data, None);
6322                 },
6323                 _ => panic!("Unexpected event"),
6324         }
6325
6326         // Complete the first payment and the RAA from the fee update.
6327         let (payment_event, send_raa_event) = {
6328                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6329                 assert_eq!(msgs.len(), 2);
6330                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6331         };
6332         let raa = match send_raa_event {
6333                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6334                 _ => panic!("Unexpected event"),
6335         };
6336         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6337         check_added_monitors!(nodes[1], 1);
6338         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6339         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6340         let events = nodes[1].node.get_and_clear_pending_events();
6341         assert_eq!(events.len(), 1);
6342         match events[0] {
6343                 Event::PendingHTLCsForwardable { .. } => {},
6344                 _ => panic!("Unexpected event"),
6345         }
6346         nodes[1].node.process_pending_htlc_forwards();
6347         let events = nodes[1].node.get_and_clear_pending_events();
6348         assert_eq!(events.len(), 1);
6349         match events[0] {
6350                 Event::PaymentReceived { .. } => {},
6351                 _ => panic!("Unexpected event"),
6352         }
6353         nodes[1].node.claim_funds(payment_preimage_1);
6354         check_added_monitors!(nodes[1], 1);
6355         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6356
6357         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6358         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6359         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6360         expect_payment_sent!(nodes[0], payment_preimage_1);
6361 }
6362
6363 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6364 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6365 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6366 // once it's freed.
6367 #[test]
6368 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6369         let chanmon_cfgs = create_chanmon_cfgs(3);
6370         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6371         // When this test was written, the default base fee floated based on the HTLC count.
6372         // It is now fixed, so we simply set the fee to the expected value here.
6373         let mut config = test_default_channel_config();
6374         config.channel_config.forwarding_fee_base_msat = 196;
6375         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6376         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6377         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6378         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6379
6380         // First nodes[1] generates an update_fee, setting the channel's
6381         // pending_update_fee.
6382         {
6383                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6384                 *feerate_lock += 20;
6385         }
6386         nodes[1].node.timer_tick_occurred();
6387         check_added_monitors!(nodes[1], 1);
6388
6389         let events = nodes[1].node.get_and_clear_pending_msg_events();
6390         assert_eq!(events.len(), 1);
6391         let (update_msg, commitment_signed) = match events[0] {
6392                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6393                         (update_fee.as_ref(), commitment_signed)
6394                 },
6395                 _ => panic!("Unexpected event"),
6396         };
6397
6398         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6399
6400         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6401         let channel_reserve = chan_stat.channel_reserve_msat;
6402         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6403         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6404
6405         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6406         let feemsat = 239;
6407         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6408         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6409         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6410         let payment_event = {
6411                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6412                 check_added_monitors!(nodes[0], 1);
6413
6414                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6415                 assert_eq!(events.len(), 1);
6416
6417                 SendEvent::from_event(events.remove(0))
6418         };
6419         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6420         check_added_monitors!(nodes[1], 0);
6421         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6422         expect_pending_htlcs_forwardable!(nodes[1]);
6423
6424         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6425         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6426
6427         // Flush the pending fee update.
6428         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6429         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6430         check_added_monitors!(nodes[2], 1);
6431         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6432         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6433         check_added_monitors!(nodes[1], 2);
6434
6435         // A final RAA message is generated to finalize the fee update.
6436         let events = nodes[1].node.get_and_clear_pending_msg_events();
6437         assert_eq!(events.len(), 1);
6438
6439         let raa_msg = match &events[0] {
6440                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6441                         msg.clone()
6442                 },
6443                 _ => panic!("Unexpected event"),
6444         };
6445
6446         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6447         check_added_monitors!(nodes[2], 1);
6448         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6449
6450         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6451         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6452         assert_eq!(process_htlc_forwards_event.len(), 1);
6453         match &process_htlc_forwards_event[0] {
6454                 &Event::PendingHTLCsForwardable { .. } => {},
6455                 _ => panic!("Unexpected event"),
6456         }
6457
6458         // In response, we call ChannelManager's process_pending_htlc_forwards
6459         nodes[1].node.process_pending_htlc_forwards();
6460         check_added_monitors!(nodes[1], 1);
6461
6462         // This causes the HTLC to be failed backwards.
6463         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6464         assert_eq!(fail_event.len(), 1);
6465         let (fail_msg, commitment_signed) = match &fail_event[0] {
6466                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6467                         assert_eq!(updates.update_add_htlcs.len(), 0);
6468                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6469                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6470                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6471                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6472                 },
6473                 _ => panic!("Unexpected event"),
6474         };
6475
6476         // Pass the failure messages back to nodes[0].
6477         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6478         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6479
6480         // Complete the HTLC failure+removal process.
6481         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6482         check_added_monitors!(nodes[0], 1);
6483         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6484         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6485         check_added_monitors!(nodes[1], 2);
6486         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6487         assert_eq!(final_raa_event.len(), 1);
6488         let raa = match &final_raa_event[0] {
6489                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6490                 _ => panic!("Unexpected event"),
6491         };
6492         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6493         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6494         check_added_monitors!(nodes[0], 1);
6495 }
6496
6497 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6498 // 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.
6499 //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.
6500
6501 #[test]
6502 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6503         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6504         let chanmon_cfgs = create_chanmon_cfgs(2);
6505         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6506         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6507         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6508         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6509
6510         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6511         route.paths[0][0].fee_msat = 100;
6512
6513         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6514                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6515         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6516         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6517 }
6518
6519 #[test]
6520 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6521         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6522         let chanmon_cfgs = create_chanmon_cfgs(2);
6523         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6524         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6525         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6526         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6527
6528         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6529         route.paths[0][0].fee_msat = 0;
6530         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6531                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6532
6533         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6534         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6535 }
6536
6537 #[test]
6538 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6539         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6540         let chanmon_cfgs = create_chanmon_cfgs(2);
6541         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6542         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6543         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6544         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6545
6546         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6547         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6548         check_added_monitors!(nodes[0], 1);
6549         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6550         updates.update_add_htlcs[0].amount_msat = 0;
6551
6552         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6553         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6554         check_closed_broadcast!(nodes[1], true).unwrap();
6555         check_added_monitors!(nodes[1], 1);
6556         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6557 }
6558
6559 #[test]
6560 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6561         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6562         //It is enforced when constructing a route.
6563         let chanmon_cfgs = create_chanmon_cfgs(2);
6564         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6565         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6566         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6567         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6568
6569         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6570                 .with_features(InvoiceFeatures::known());
6571         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6572         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6573         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6574                 assert_eq!(err, &"Channel CLTV overflowed?"));
6575 }
6576
6577 #[test]
6578 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6579         //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.
6580         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6581         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6582         let chanmon_cfgs = create_chanmon_cfgs(2);
6583         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6584         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6585         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6586         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6587         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6588
6589         for i in 0..max_accepted_htlcs {
6590                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6591                 let payment_event = {
6592                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6593                         check_added_monitors!(nodes[0], 1);
6594
6595                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6596                         assert_eq!(events.len(), 1);
6597                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6598                                 assert_eq!(htlcs[0].htlc_id, i);
6599                         } else {
6600                                 assert!(false);
6601                         }
6602                         SendEvent::from_event(events.remove(0))
6603                 };
6604                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6605                 check_added_monitors!(nodes[1], 0);
6606                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6607
6608                 expect_pending_htlcs_forwardable!(nodes[1]);
6609                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6610         }
6611         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6612         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6613                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6614
6615         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6616         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6617 }
6618
6619 #[test]
6620 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6621         //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.
6622         let chanmon_cfgs = create_chanmon_cfgs(2);
6623         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6624         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6625         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6626         let channel_value = 100000;
6627         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6628         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6629
6630         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6631
6632         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6633         // Manually create a route over our max in flight (which our router normally automatically
6634         // limits us to.
6635         route.paths[0][0].fee_msat =  max_in_flight + 1;
6636         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6637                 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)));
6638
6639         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6640         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);
6641
6642         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6643 }
6644
6645 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6646 #[test]
6647 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6648         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6649         let chanmon_cfgs = create_chanmon_cfgs(2);
6650         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6651         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6652         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6653         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6654         let htlc_minimum_msat: u64;
6655         {
6656                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6657                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6658                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6659         }
6660
6661         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6662         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6663         check_added_monitors!(nodes[0], 1);
6664         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6665         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6666         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6667         assert!(nodes[1].node.list_channels().is_empty());
6668         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6669         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()));
6670         check_added_monitors!(nodes[1], 1);
6671         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6672 }
6673
6674 #[test]
6675 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6676         //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
6677         let chanmon_cfgs = create_chanmon_cfgs(2);
6678         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6679         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6680         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6681         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6682
6683         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6684         let channel_reserve = chan_stat.channel_reserve_msat;
6685         let feerate = get_feerate!(nodes[0], chan.2);
6686         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6687         // The 2* and +1 are for the fee spike reserve.
6688         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6689
6690         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6691         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6692         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6693         check_added_monitors!(nodes[0], 1);
6694         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6695
6696         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6697         // at this time channel-initiatee receivers are not required to enforce that senders
6698         // respect the fee_spike_reserve.
6699         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6700         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6701
6702         assert!(nodes[1].node.list_channels().is_empty());
6703         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6704         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6705         check_added_monitors!(nodes[1], 1);
6706         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6707 }
6708
6709 #[test]
6710 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6711         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6712         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6713         let chanmon_cfgs = create_chanmon_cfgs(2);
6714         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6715         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6716         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6717         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6718
6719         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6720         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6721         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6722         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6723         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6724         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6725
6726         let mut msg = msgs::UpdateAddHTLC {
6727                 channel_id: chan.2,
6728                 htlc_id: 0,
6729                 amount_msat: 1000,
6730                 payment_hash: our_payment_hash,
6731                 cltv_expiry: htlc_cltv,
6732                 onion_routing_packet: onion_packet.clone(),
6733         };
6734
6735         for i in 0..super::channel::OUR_MAX_HTLCS {
6736                 msg.htlc_id = i as u64;
6737                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6738         }
6739         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6740         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6741
6742         assert!(nodes[1].node.list_channels().is_empty());
6743         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6744         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6745         check_added_monitors!(nodes[1], 1);
6746         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6747 }
6748
6749 #[test]
6750 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6751         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6752         let chanmon_cfgs = create_chanmon_cfgs(2);
6753         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6754         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6755         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6756         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6757
6758         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6759         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6760         check_added_monitors!(nodes[0], 1);
6761         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6762         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6763         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6764
6765         assert!(nodes[1].node.list_channels().is_empty());
6766         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6767         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6768         check_added_monitors!(nodes[1], 1);
6769         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6770 }
6771
6772 #[test]
6773 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6774         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6775         let chanmon_cfgs = create_chanmon_cfgs(2);
6776         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6777         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6778         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6779
6780         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6781         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6782         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6783         check_added_monitors!(nodes[0], 1);
6784         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6785         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6786         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6787
6788         assert!(nodes[1].node.list_channels().is_empty());
6789         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6790         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6791         check_added_monitors!(nodes[1], 1);
6792         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6793 }
6794
6795 #[test]
6796 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6797         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6798         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6799         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6800         let chanmon_cfgs = create_chanmon_cfgs(2);
6801         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6802         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6803         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6804
6805         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6806         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6807         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6808         check_added_monitors!(nodes[0], 1);
6809         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6810         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6811
6812         //Disconnect and Reconnect
6813         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6814         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6815         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6816         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6817         assert_eq!(reestablish_1.len(), 1);
6818         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6819         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6820         assert_eq!(reestablish_2.len(), 1);
6821         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6822         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6823         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6824         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6825
6826         //Resend HTLC
6827         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6828         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6829         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6830         check_added_monitors!(nodes[1], 1);
6831         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6832
6833         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6834
6835         assert!(nodes[1].node.list_channels().is_empty());
6836         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6837         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6838         check_added_monitors!(nodes[1], 1);
6839         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6840 }
6841
6842 #[test]
6843 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6844         //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.
6845
6846         let chanmon_cfgs = create_chanmon_cfgs(2);
6847         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6848         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6849         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6850         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6851         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6852         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6853
6854         check_added_monitors!(nodes[0], 1);
6855         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6856         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6857
6858         let update_msg = msgs::UpdateFulfillHTLC{
6859                 channel_id: chan.2,
6860                 htlc_id: 0,
6861                 payment_preimage: our_payment_preimage,
6862         };
6863
6864         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6865
6866         assert!(nodes[0].node.list_channels().is_empty());
6867         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6868         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()));
6869         check_added_monitors!(nodes[0], 1);
6870         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6871 }
6872
6873 #[test]
6874 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6875         //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.
6876
6877         let chanmon_cfgs = create_chanmon_cfgs(2);
6878         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6879         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6880         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6881         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6882
6883         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6884         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6885         check_added_monitors!(nodes[0], 1);
6886         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6887         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6888
6889         let update_msg = msgs::UpdateFailHTLC{
6890                 channel_id: chan.2,
6891                 htlc_id: 0,
6892                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6893         };
6894
6895         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6896
6897         assert!(nodes[0].node.list_channels().is_empty());
6898         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6899         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()));
6900         check_added_monitors!(nodes[0], 1);
6901         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6902 }
6903
6904 #[test]
6905 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6906         //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.
6907
6908         let chanmon_cfgs = create_chanmon_cfgs(2);
6909         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6910         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6911         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6912         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6913
6914         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6915         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6916         check_added_monitors!(nodes[0], 1);
6917         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6918         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6919         let update_msg = msgs::UpdateFailMalformedHTLC{
6920                 channel_id: chan.2,
6921                 htlc_id: 0,
6922                 sha256_of_onion: [1; 32],
6923                 failure_code: 0x8000,
6924         };
6925
6926         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6927
6928         assert!(nodes[0].node.list_channels().is_empty());
6929         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6930         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()));
6931         check_added_monitors!(nodes[0], 1);
6932         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6933 }
6934
6935 #[test]
6936 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6937         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6938
6939         let chanmon_cfgs = create_chanmon_cfgs(2);
6940         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6941         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6942         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6943         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6944
6945         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6946
6947         nodes[1].node.claim_funds(our_payment_preimage);
6948         check_added_monitors!(nodes[1], 1);
6949         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6950
6951         let events = nodes[1].node.get_and_clear_pending_msg_events();
6952         assert_eq!(events.len(), 1);
6953         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6954                 match events[0] {
6955                         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, .. } } => {
6956                                 assert!(update_add_htlcs.is_empty());
6957                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6958                                 assert!(update_fail_htlcs.is_empty());
6959                                 assert!(update_fail_malformed_htlcs.is_empty());
6960                                 assert!(update_fee.is_none());
6961                                 update_fulfill_htlcs[0].clone()
6962                         },
6963                         _ => panic!("Unexpected event"),
6964                 }
6965         };
6966
6967         update_fulfill_msg.htlc_id = 1;
6968
6969         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6970
6971         assert!(nodes[0].node.list_channels().is_empty());
6972         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6973         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6974         check_added_monitors!(nodes[0], 1);
6975         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6976 }
6977
6978 #[test]
6979 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6980         //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.
6981
6982         let chanmon_cfgs = create_chanmon_cfgs(2);
6983         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6984         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6985         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6986         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6987
6988         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6989
6990         nodes[1].node.claim_funds(our_payment_preimage);
6991         check_added_monitors!(nodes[1], 1);
6992         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6993
6994         let events = nodes[1].node.get_and_clear_pending_msg_events();
6995         assert_eq!(events.len(), 1);
6996         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6997                 match events[0] {
6998                         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, .. } } => {
6999                                 assert!(update_add_htlcs.is_empty());
7000                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7001                                 assert!(update_fail_htlcs.is_empty());
7002                                 assert!(update_fail_malformed_htlcs.is_empty());
7003                                 assert!(update_fee.is_none());
7004                                 update_fulfill_htlcs[0].clone()
7005                         },
7006                         _ => panic!("Unexpected event"),
7007                 }
7008         };
7009
7010         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7011
7012         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7013
7014         assert!(nodes[0].node.list_channels().is_empty());
7015         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7016         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7017         check_added_monitors!(nodes[0], 1);
7018         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7019 }
7020
7021 #[test]
7022 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7023         //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.
7024
7025         let chanmon_cfgs = create_chanmon_cfgs(2);
7026         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7027         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7028         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7029         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7030
7031         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7032         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7033         check_added_monitors!(nodes[0], 1);
7034
7035         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7036         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7037
7038         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7039         check_added_monitors!(nodes[1], 0);
7040         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7041
7042         let events = nodes[1].node.get_and_clear_pending_msg_events();
7043
7044         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7045                 match events[0] {
7046                         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, .. } } => {
7047                                 assert!(update_add_htlcs.is_empty());
7048                                 assert!(update_fulfill_htlcs.is_empty());
7049                                 assert!(update_fail_htlcs.is_empty());
7050                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7051                                 assert!(update_fee.is_none());
7052                                 update_fail_malformed_htlcs[0].clone()
7053                         },
7054                         _ => panic!("Unexpected event"),
7055                 }
7056         };
7057         update_msg.failure_code &= !0x8000;
7058         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7059
7060         assert!(nodes[0].node.list_channels().is_empty());
7061         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7062         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7063         check_added_monitors!(nodes[0], 1);
7064         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7065 }
7066
7067 #[test]
7068 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7069         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7070         //    * 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.
7071
7072         let chanmon_cfgs = create_chanmon_cfgs(3);
7073         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7074         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7075         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7076         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7077         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7078
7079         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7080
7081         //First hop
7082         let mut payment_event = {
7083                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7084                 check_added_monitors!(nodes[0], 1);
7085                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7086                 assert_eq!(events.len(), 1);
7087                 SendEvent::from_event(events.remove(0))
7088         };
7089         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7090         check_added_monitors!(nodes[1], 0);
7091         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7092         expect_pending_htlcs_forwardable!(nodes[1]);
7093         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7094         assert_eq!(events_2.len(), 1);
7095         check_added_monitors!(nodes[1], 1);
7096         payment_event = SendEvent::from_event(events_2.remove(0));
7097         assert_eq!(payment_event.msgs.len(), 1);
7098
7099         //Second Hop
7100         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7101         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7102         check_added_monitors!(nodes[2], 0);
7103         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7104
7105         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7106         assert_eq!(events_3.len(), 1);
7107         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7108                 match events_3[0] {
7109                         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 } } => {
7110                                 assert!(update_add_htlcs.is_empty());
7111                                 assert!(update_fulfill_htlcs.is_empty());
7112                                 assert!(update_fail_htlcs.is_empty());
7113                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7114                                 assert!(update_fee.is_none());
7115                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7116                         },
7117                         _ => panic!("Unexpected event"),
7118                 }
7119         };
7120
7121         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7122
7123         check_added_monitors!(nodes[1], 0);
7124         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7125         expect_pending_htlcs_forwardable!(nodes[1]);
7126         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7127         assert_eq!(events_4.len(), 1);
7128
7129         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7130         match events_4[0] {
7131                 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, .. } } => {
7132                         assert!(update_add_htlcs.is_empty());
7133                         assert!(update_fulfill_htlcs.is_empty());
7134                         assert_eq!(update_fail_htlcs.len(), 1);
7135                         assert!(update_fail_malformed_htlcs.is_empty());
7136                         assert!(update_fee.is_none());
7137                 },
7138                 _ => panic!("Unexpected event"),
7139         };
7140
7141         check_added_monitors!(nodes[1], 1);
7142 }
7143
7144 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7145         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7146         // 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
7147         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7148
7149         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7150         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7151         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7152         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7153         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7154         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7155
7156         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7157
7158         // We route 2 dust-HTLCs between A and B
7159         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7160         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7161         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7162
7163         // Cache one local commitment tx as previous
7164         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7165
7166         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7167         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7168         check_added_monitors!(nodes[1], 0);
7169         expect_pending_htlcs_forwardable!(nodes[1]);
7170         check_added_monitors!(nodes[1], 1);
7171
7172         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7173         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7174         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7175         check_added_monitors!(nodes[0], 1);
7176
7177         // Cache one local commitment tx as lastest
7178         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7179
7180         let events = nodes[0].node.get_and_clear_pending_msg_events();
7181         match events[0] {
7182                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7183                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7184                 },
7185                 _ => panic!("Unexpected event"),
7186         }
7187         match events[1] {
7188                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7189                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7190                 },
7191                 _ => panic!("Unexpected event"),
7192         }
7193
7194         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7195         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7196         if announce_latest {
7197                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7198         } else {
7199                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7200         }
7201
7202         check_closed_broadcast!(nodes[0], true);
7203         check_added_monitors!(nodes[0], 1);
7204         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7205
7206         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7207         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7208         let events = nodes[0].node.get_and_clear_pending_events();
7209         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7210         assert_eq!(events.len(), 2);
7211         let mut first_failed = false;
7212         for event in events {
7213                 match event {
7214                         Event::PaymentPathFailed { payment_hash, .. } => {
7215                                 if payment_hash == payment_hash_1 {
7216                                         assert!(!first_failed);
7217                                         first_failed = true;
7218                                 } else {
7219                                         assert_eq!(payment_hash, payment_hash_2);
7220                                 }
7221                         }
7222                         _ => panic!("Unexpected event"),
7223                 }
7224         }
7225 }
7226
7227 #[test]
7228 fn test_failure_delay_dust_htlc_local_commitment() {
7229         do_test_failure_delay_dust_htlc_local_commitment(true);
7230         do_test_failure_delay_dust_htlc_local_commitment(false);
7231 }
7232
7233 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7234         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7235         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7236         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7237         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7238         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7239         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7240
7241         let chanmon_cfgs = create_chanmon_cfgs(3);
7242         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7243         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7244         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7245         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7246
7247         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7248
7249         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7250         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7251
7252         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7253         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7254
7255         // We revoked bs_commitment_tx
7256         if revoked {
7257                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7258                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7259         }
7260
7261         let mut timeout_tx = Vec::new();
7262         if local {
7263                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7264                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7265                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7266                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7267                 expect_payment_failed!(nodes[0], dust_hash, true);
7268
7269                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7270                 check_closed_broadcast!(nodes[0], true);
7271                 check_added_monitors!(nodes[0], 1);
7272                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7273                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7274                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7275                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7276                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7277                 mine_transaction(&nodes[0], &timeout_tx[0]);
7278                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7279                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7280         } else {
7281                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7282                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7283                 check_closed_broadcast!(nodes[0], true);
7284                 check_added_monitors!(nodes[0], 1);
7285                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7286                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7287
7288                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7289                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7290                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7291                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7292                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7293                 // dust HTLC should have been failed.
7294                 expect_payment_failed!(nodes[0], dust_hash, true);
7295
7296                 if !revoked {
7297                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7298                 } else {
7299                         assert_eq!(timeout_tx[0].lock_time, 0);
7300                 }
7301                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7302                 mine_transaction(&nodes[0], &timeout_tx[0]);
7303                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7304                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7305                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7306         }
7307 }
7308
7309 #[test]
7310 fn test_sweep_outbound_htlc_failure_update() {
7311         do_test_sweep_outbound_htlc_failure_update(false, true);
7312         do_test_sweep_outbound_htlc_failure_update(false, false);
7313         do_test_sweep_outbound_htlc_failure_update(true, false);
7314 }
7315
7316 #[test]
7317 fn test_user_configurable_csv_delay() {
7318         // We test our channel constructors yield errors when we pass them absurd csv delay
7319
7320         let mut low_our_to_self_config = UserConfig::default();
7321         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7322         let mut high_their_to_self_config = UserConfig::default();
7323         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7324         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7325         let chanmon_cfgs = create_chanmon_cfgs(2);
7326         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7327         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7328         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7329
7330         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7331         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7332                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7333                 &low_our_to_self_config, 0, 42)
7334         {
7335                 match error {
7336                         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())); },
7337                         _ => panic!("Unexpected event"),
7338                 }
7339         } else { assert!(false) }
7340
7341         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7342         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7343         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7344         open_channel.to_self_delay = 200;
7345         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7346                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7347                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7348         {
7349                 match error {
7350                         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()));  },
7351                         _ => panic!("Unexpected event"),
7352                 }
7353         } else { assert!(false); }
7354
7355         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7356         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7357         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()));
7358         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7359         accept_channel.to_self_delay = 200;
7360         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7361         let reason_msg;
7362         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7363                 match action {
7364                         &ErrorAction::SendErrorMessage { ref msg } => {
7365                                 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()));
7366                                 reason_msg = msg.data.clone();
7367                         },
7368                         _ => { panic!(); }
7369                 }
7370         } else { panic!(); }
7371         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7372
7373         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7374         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7375         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7376         open_channel.to_self_delay = 200;
7377         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7378                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7379                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7380         {
7381                 match error {
7382                         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())); },
7383                         _ => panic!("Unexpected event"),
7384                 }
7385         } else { assert!(false); }
7386 }
7387
7388 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7389         // When we get a data_loss_protect proving we're behind, we immediately panic as the
7390         // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7391         // panic message informs the user they should force-close without broadcasting, which is tested
7392         // if `reconnect_panicing` is not set.
7393         let persister;
7394         let logger;
7395         let fee_estimator;
7396         let tx_broadcaster;
7397         let chain_source;
7398         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7399         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7400         // during signing due to revoked tx
7401         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7402         let keys_manager = &chanmon_cfgs[0].keys_manager;
7403         let monitor;
7404         let node_state_0;
7405         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7406         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7407         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7408
7409         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7410
7411         // Cache node A state before any channel update
7412         let previous_node_state = nodes[0].node.encode();
7413         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7414         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7415
7416         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7417         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7418
7419         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7420         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7421
7422         // Restore node A from previous state
7423         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7424         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7425         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7426         tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7427         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7428         persister = test_utils::TestPersister::new();
7429         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7430         node_state_0 = {
7431                 let mut channel_monitors = HashMap::new();
7432                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7433                 <(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 {
7434                         keys_manager: keys_manager,
7435                         fee_estimator: &fee_estimator,
7436                         chain_monitor: &monitor,
7437                         logger: &logger,
7438                         tx_broadcaster: &tx_broadcaster,
7439                         default_config: UserConfig::default(),
7440                         channel_monitors,
7441                 }).unwrap().1
7442         };
7443         nodes[0].node = &node_state_0;
7444         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7445         nodes[0].chain_monitor = &monitor;
7446         nodes[0].chain_source = &chain_source;
7447
7448         check_added_monitors!(nodes[0], 1);
7449
7450         if reconnect_panicing {
7451                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7452                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7453
7454                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7455
7456                 // Check we close channel detecting A is fallen-behind
7457                 // Check that we sent the warning message when we detected that A has fallen behind,
7458                 // and give the possibility for A to recover from the warning.
7459                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7460                 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7461                 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7462
7463                 {
7464                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7465                         // The node B should not broadcast the transaction to force close the channel!
7466                         assert!(node_txn.is_empty());
7467                 }
7468
7469                 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7470                 // Check A panics upon seeing proof it has fallen behind.
7471                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7472                 return; // By this point we should have panic'ed!
7473         }
7474
7475         nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7476         check_added_monitors!(nodes[0], 1);
7477         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7478         {
7479                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7480                 assert_eq!(node_txn.len(), 0);
7481         }
7482
7483         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7484                 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7485                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7486                         match action {
7487                                 &ErrorAction::SendErrorMessage { ref msg } => {
7488                                         assert_eq!(msg.data, "Channel force-closed");
7489                                 },
7490                                 _ => panic!("Unexpected event!"),
7491                         }
7492                 } else {
7493                         panic!("Unexpected event {:?}", msg)
7494                 }
7495         }
7496
7497         // after the warning message sent by B, we should not able to
7498         // use the channel, or reconnect with success to the channel.
7499         assert!(nodes[0].node.list_usable_channels().is_empty());
7500         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7501         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7502         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7503
7504         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7505         let mut err_msgs_0 = Vec::with_capacity(1);
7506         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7507                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7508                         match action {
7509                                 &ErrorAction::SendErrorMessage { ref msg } => {
7510                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7511                                         err_msgs_0.push(msg.clone());
7512                                 },
7513                                 _ => panic!("Unexpected event!"),
7514                         }
7515                 } else {
7516                         panic!("Unexpected event!");
7517                 }
7518         }
7519         assert_eq!(err_msgs_0.len(), 1);
7520         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7521         assert!(nodes[1].node.list_usable_channels().is_empty());
7522         check_added_monitors!(nodes[1], 1);
7523         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7524         check_closed_broadcast!(nodes[1], false);
7525 }
7526
7527 #[test]
7528 #[should_panic]
7529 fn test_data_loss_protect_showing_stale_state_panics() {
7530         do_test_data_loss_protect(true);
7531 }
7532
7533 #[test]
7534 fn test_force_close_without_broadcast() {
7535         do_test_data_loss_protect(false);
7536 }
7537
7538 #[test]
7539 fn test_check_htlc_underpaying() {
7540         // Send payment through A -> B but A is maliciously
7541         // sending a probe payment (i.e less than expected value0
7542         // to B, B should refuse payment.
7543
7544         let chanmon_cfgs = create_chanmon_cfgs(2);
7545         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7546         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7547         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7548
7549         // Create some initial channels
7550         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7551
7552         let scorer = test_utils::TestScorer::with_penalty(0);
7553         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7554         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7555         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();
7556         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7557         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7558         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7559         check_added_monitors!(nodes[0], 1);
7560
7561         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7562         assert_eq!(events.len(), 1);
7563         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7564         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7565         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7566
7567         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7568         // and then will wait a second random delay before failing the HTLC back:
7569         expect_pending_htlcs_forwardable!(nodes[1]);
7570         expect_pending_htlcs_forwardable!(nodes[1]);
7571
7572         // Node 3 is expecting payment of 100_000 but received 10_000,
7573         // it should fail htlc like we didn't know the preimage.
7574         nodes[1].node.process_pending_htlc_forwards();
7575
7576         let events = nodes[1].node.get_and_clear_pending_msg_events();
7577         assert_eq!(events.len(), 1);
7578         let (update_fail_htlc, commitment_signed) = match events[0] {
7579                 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 } } => {
7580                         assert!(update_add_htlcs.is_empty());
7581                         assert!(update_fulfill_htlcs.is_empty());
7582                         assert_eq!(update_fail_htlcs.len(), 1);
7583                         assert!(update_fail_malformed_htlcs.is_empty());
7584                         assert!(update_fee.is_none());
7585                         (update_fail_htlcs[0].clone(), commitment_signed)
7586                 },
7587                 _ => panic!("Unexpected event"),
7588         };
7589         check_added_monitors!(nodes[1], 1);
7590
7591         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7592         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7593
7594         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7595         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7596         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7597         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7598 }
7599
7600 #[test]
7601 fn test_announce_disable_channels() {
7602         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7603         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7604
7605         let chanmon_cfgs = create_chanmon_cfgs(2);
7606         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7607         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7608         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7609
7610         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7611         create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7612         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7613
7614         // Disconnect peers
7615         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7616         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7617
7618         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7619         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7620         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7621         assert_eq!(msg_events.len(), 3);
7622         let mut chans_disabled = HashMap::new();
7623         for e in msg_events {
7624                 match e {
7625                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7626                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7627                                 // Check that each channel gets updated exactly once
7628                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7629                                         panic!("Generated ChannelUpdate for wrong chan!");
7630                                 }
7631                         },
7632                         _ => panic!("Unexpected event"),
7633                 }
7634         }
7635         // Reconnect peers
7636         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7637         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7638         assert_eq!(reestablish_1.len(), 3);
7639         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7640         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7641         assert_eq!(reestablish_2.len(), 3);
7642
7643         // Reestablish chan_1
7644         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7645         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7646         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7647         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7648         // Reestablish chan_2
7649         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7650         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7651         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7652         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7653         // Reestablish chan_3
7654         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7655         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7656         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7657         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7658
7659         nodes[0].node.timer_tick_occurred();
7660         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7661         nodes[0].node.timer_tick_occurred();
7662         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7663         assert_eq!(msg_events.len(), 3);
7664         for e in msg_events {
7665                 match e {
7666                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7667                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7668                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7669                                         // Each update should have a higher timestamp than the previous one, replacing
7670                                         // the old one.
7671                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7672                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7673                                 }
7674                         },
7675                         _ => panic!("Unexpected event"),
7676                 }
7677         }
7678         // Check that each channel gets updated exactly once
7679         assert!(chans_disabled.is_empty());
7680 }
7681
7682 #[test]
7683 fn test_bump_penalty_txn_on_revoked_commitment() {
7684         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7685         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7686
7687         let chanmon_cfgs = create_chanmon_cfgs(2);
7688         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7689         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7690         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7691
7692         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7693
7694         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7695         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7696                 .with_features(InvoiceFeatures::known());
7697         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7698         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7699
7700         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7701         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7702         assert_eq!(revoked_txn[0].output.len(), 4);
7703         assert_eq!(revoked_txn[0].input.len(), 1);
7704         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7705         let revoked_txid = revoked_txn[0].txid();
7706
7707         let mut penalty_sum = 0;
7708         for outp in revoked_txn[0].output.iter() {
7709                 if outp.script_pubkey.is_v0_p2wsh() {
7710                         penalty_sum += outp.value;
7711                 }
7712         }
7713
7714         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7715         let header_114 = connect_blocks(&nodes[1], 14);
7716
7717         // Actually revoke tx by claiming a HTLC
7718         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7719         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7720         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7721         check_added_monitors!(nodes[1], 1);
7722
7723         // One or more justice tx should have been broadcast, check it
7724         let penalty_1;
7725         let feerate_1;
7726         {
7727                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7728                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7729                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7730                 assert_eq!(node_txn[0].output.len(), 1);
7731                 check_spends!(node_txn[0], revoked_txn[0]);
7732                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7733                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7734                 penalty_1 = node_txn[0].txid();
7735                 node_txn.clear();
7736         };
7737
7738         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7739         connect_blocks(&nodes[1], 15);
7740         let mut penalty_2 = penalty_1;
7741         let mut feerate_2 = 0;
7742         {
7743                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7744                 assert_eq!(node_txn.len(), 1);
7745                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7746                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7747                         assert_eq!(node_txn[0].output.len(), 1);
7748                         check_spends!(node_txn[0], revoked_txn[0]);
7749                         penalty_2 = node_txn[0].txid();
7750                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7751                         assert_ne!(penalty_2, penalty_1);
7752                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7753                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7754                         // Verify 25% bump heuristic
7755                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7756                         node_txn.clear();
7757                 }
7758         }
7759         assert_ne!(feerate_2, 0);
7760
7761         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7762         connect_blocks(&nodes[1], 1);
7763         let penalty_3;
7764         let mut feerate_3 = 0;
7765         {
7766                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7767                 assert_eq!(node_txn.len(), 1);
7768                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7769                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7770                         assert_eq!(node_txn[0].output.len(), 1);
7771                         check_spends!(node_txn[0], revoked_txn[0]);
7772                         penalty_3 = node_txn[0].txid();
7773                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7774                         assert_ne!(penalty_3, penalty_2);
7775                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7776                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7777                         // Verify 25% bump heuristic
7778                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7779                         node_txn.clear();
7780                 }
7781         }
7782         assert_ne!(feerate_3, 0);
7783
7784         nodes[1].node.get_and_clear_pending_events();
7785         nodes[1].node.get_and_clear_pending_msg_events();
7786 }
7787
7788 #[test]
7789 fn test_bump_penalty_txn_on_revoked_htlcs() {
7790         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7791         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7792
7793         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7794         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7795         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7796         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7797         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7798
7799         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7800         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7801         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7802         let scorer = test_utils::TestScorer::with_penalty(0);
7803         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7804         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7805                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7806         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7807         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7808         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7809                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7810         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7811
7812         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7813         assert_eq!(revoked_local_txn[0].input.len(), 1);
7814         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7815
7816         // Revoke local commitment tx
7817         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7818
7819         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7820         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7821         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7822         check_closed_broadcast!(nodes[1], true);
7823         check_added_monitors!(nodes[1], 1);
7824         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7825         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7826
7827         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7828         assert_eq!(revoked_htlc_txn.len(), 3);
7829         check_spends!(revoked_htlc_txn[1], chan.3);
7830
7831         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7832         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7833         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7834
7835         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7836         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7837         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7838         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7839
7840         // Broadcast set of revoked txn on A
7841         let hash_128 = connect_blocks(&nodes[0], 40);
7842         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7843         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7844         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7845         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7846         let events = nodes[0].node.get_and_clear_pending_events();
7847         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7848         match events[1] {
7849                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7850                 _ => panic!("Unexpected event"),
7851         }
7852         let first;
7853         let feerate_1;
7854         let penalty_txn;
7855         {
7856                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7857                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7858                 // Verify claim tx are spending revoked HTLC txn
7859
7860                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7861                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7862                 // which are included in the same block (they are broadcasted because we scan the
7863                 // transactions linearly and generate claims as we go, they likely should be removed in the
7864                 // future).
7865                 assert_eq!(node_txn[0].input.len(), 1);
7866                 check_spends!(node_txn[0], revoked_local_txn[0]);
7867                 assert_eq!(node_txn[1].input.len(), 1);
7868                 check_spends!(node_txn[1], revoked_local_txn[0]);
7869                 assert_eq!(node_txn[2].input.len(), 1);
7870                 check_spends!(node_txn[2], revoked_local_txn[0]);
7871
7872                 // Each of the three justice transactions claim a separate (single) output of the three
7873                 // available, which we check here:
7874                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7875                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7876                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7877
7878                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7879                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7880
7881                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7882                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7883                 // a remote commitment tx has already been confirmed).
7884                 check_spends!(node_txn[3], chan.3);
7885
7886                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7887                 // output, checked above).
7888                 assert_eq!(node_txn[4].input.len(), 2);
7889                 assert_eq!(node_txn[4].output.len(), 1);
7890                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7891
7892                 first = node_txn[4].txid();
7893                 // Store both feerates for later comparison
7894                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7895                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7896                 penalty_txn = vec![node_txn[2].clone()];
7897                 node_txn.clear();
7898         }
7899
7900         // Connect one more block to see if bumped penalty are issued for HTLC txn
7901         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7902         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7903         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7904         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7905         {
7906                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7907                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7908
7909                 check_spends!(node_txn[0], revoked_local_txn[0]);
7910                 check_spends!(node_txn[1], revoked_local_txn[0]);
7911                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7912                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7913                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7914                 } else {
7915                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7916                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7917                 }
7918
7919                 node_txn.clear();
7920         };
7921
7922         // Few more blocks to confirm penalty txn
7923         connect_blocks(&nodes[0], 4);
7924         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7925         let header_144 = connect_blocks(&nodes[0], 9);
7926         let node_txn = {
7927                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7928                 assert_eq!(node_txn.len(), 1);
7929
7930                 assert_eq!(node_txn[0].input.len(), 2);
7931                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7932                 // Verify bumped tx is different and 25% bump heuristic
7933                 assert_ne!(first, node_txn[0].txid());
7934                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7935                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7936                 assert!(feerate_2 * 100 > feerate_1 * 125);
7937                 let txn = vec![node_txn[0].clone()];
7938                 node_txn.clear();
7939                 txn
7940         };
7941         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7942         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7943         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7944         connect_blocks(&nodes[0], 20);
7945         {
7946                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7947                 // We verify than no new transaction has been broadcast because previously
7948                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7949                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7950                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7951                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7952                 // up bumped justice generation.
7953                 assert_eq!(node_txn.len(), 0);
7954                 node_txn.clear();
7955         }
7956         check_closed_broadcast!(nodes[0], true);
7957         check_added_monitors!(nodes[0], 1);
7958 }
7959
7960 #[test]
7961 fn test_bump_penalty_txn_on_remote_commitment() {
7962         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7963         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7964
7965         // Create 2 HTLCs
7966         // Provide preimage for one
7967         // Check aggregation
7968
7969         let chanmon_cfgs = create_chanmon_cfgs(2);
7970         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7971         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7972         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7973
7974         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7975         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7976         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7977
7978         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7979         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7980         assert_eq!(remote_txn[0].output.len(), 4);
7981         assert_eq!(remote_txn[0].input.len(), 1);
7982         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7983
7984         // Claim a HTLC without revocation (provide B monitor with preimage)
7985         nodes[1].node.claim_funds(payment_preimage);
7986         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7987         mine_transaction(&nodes[1], &remote_txn[0]);
7988         check_added_monitors!(nodes[1], 2);
7989         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7990
7991         // One or more claim tx should have been broadcast, check it
7992         let timeout;
7993         let preimage;
7994         let preimage_bump;
7995         let feerate_timeout;
7996         let feerate_preimage;
7997         {
7998                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7999                 // 9 transactions including:
8000                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8001                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8002                 // 2 * HTLC-Success (one RBF bump we'll check later)
8003                 // 1 * HTLC-Timeout
8004                 assert_eq!(node_txn.len(), 8);
8005                 assert_eq!(node_txn[0].input.len(), 1);
8006                 assert_eq!(node_txn[6].input.len(), 1);
8007                 check_spends!(node_txn[0], remote_txn[0]);
8008                 check_spends!(node_txn[6], remote_txn[0]);
8009
8010                 check_spends!(node_txn[1], chan.3);
8011                 check_spends!(node_txn[2], node_txn[1]);
8012
8013                 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
8014                         preimage_bump = node_txn[3].clone();
8015                         check_spends!(node_txn[3], remote_txn[0]);
8016
8017                         assert_eq!(node_txn[1], node_txn[4]);
8018                         assert_eq!(node_txn[2], node_txn[5]);
8019                 } else {
8020                         preimage_bump = node_txn[7].clone();
8021                         check_spends!(node_txn[7], remote_txn[0]);
8022                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8023
8024                         assert_eq!(node_txn[1], node_txn[3]);
8025                         assert_eq!(node_txn[2], node_txn[4]);
8026                 }
8027
8028                 timeout = node_txn[6].txid();
8029                 let index = node_txn[6].input[0].previous_output.vout;
8030                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8031                 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8032
8033                 preimage = node_txn[0].txid();
8034                 let index = node_txn[0].input[0].previous_output.vout;
8035                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8036                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8037
8038                 node_txn.clear();
8039         };
8040         assert_ne!(feerate_timeout, 0);
8041         assert_ne!(feerate_preimage, 0);
8042
8043         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8044         connect_blocks(&nodes[1], 15);
8045         {
8046                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8047                 assert_eq!(node_txn.len(), 1);
8048                 assert_eq!(node_txn[0].input.len(), 1);
8049                 assert_eq!(preimage_bump.input.len(), 1);
8050                 check_spends!(node_txn[0], remote_txn[0]);
8051                 check_spends!(preimage_bump, remote_txn[0]);
8052
8053                 let index = preimage_bump.input[0].previous_output.vout;
8054                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8055                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8056                 assert!(new_feerate * 100 > feerate_timeout * 125);
8057                 assert_ne!(timeout, preimage_bump.txid());
8058
8059                 let index = node_txn[0].input[0].previous_output.vout;
8060                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8061                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8062                 assert!(new_feerate * 100 > feerate_preimage * 125);
8063                 assert_ne!(preimage, node_txn[0].txid());
8064
8065                 node_txn.clear();
8066         }
8067
8068         nodes[1].node.get_and_clear_pending_events();
8069         nodes[1].node.get_and_clear_pending_msg_events();
8070 }
8071
8072 #[test]
8073 fn test_counterparty_raa_skip_no_crash() {
8074         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8075         // commitment transaction, we would have happily carried on and provided them the next
8076         // commitment transaction based on one RAA forward. This would probably eventually have led to
8077         // channel closure, but it would not have resulted in funds loss. Still, our
8078         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8079         // check simply that the channel is closed in response to such an RAA, but don't check whether
8080         // we decide to punish our counterparty for revoking their funds (as we don't currently
8081         // implement that).
8082         let chanmon_cfgs = create_chanmon_cfgs(2);
8083         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8084         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8085         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8086         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8087
8088         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8089         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8090
8091         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8092
8093         // Make signer believe we got a counterparty signature, so that it allows the revocation
8094         keys.get_enforcement_state().last_holder_commitment -= 1;
8095         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8096
8097         // Must revoke without gaps
8098         keys.get_enforcement_state().last_holder_commitment -= 1;
8099         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8100
8101         keys.get_enforcement_state().last_holder_commitment -= 1;
8102         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8103                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8104
8105         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8106                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8107         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8108         check_added_monitors!(nodes[1], 1);
8109         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8110 }
8111
8112 #[test]
8113 fn test_bump_txn_sanitize_tracking_maps() {
8114         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8115         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8116
8117         let chanmon_cfgs = create_chanmon_cfgs(2);
8118         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8119         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8120         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8121
8122         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8123         // Lock HTLC in both directions
8124         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8125         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8126
8127         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8128         assert_eq!(revoked_local_txn[0].input.len(), 1);
8129         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8130
8131         // Revoke local commitment tx
8132         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8133
8134         // Broadcast set of revoked txn on A
8135         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8136         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8137         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8138
8139         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8140         check_closed_broadcast!(nodes[0], true);
8141         check_added_monitors!(nodes[0], 1);
8142         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8143         let penalty_txn = {
8144                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8145                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8146                 check_spends!(node_txn[0], revoked_local_txn[0]);
8147                 check_spends!(node_txn[1], revoked_local_txn[0]);
8148                 check_spends!(node_txn[2], revoked_local_txn[0]);
8149                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8150                 node_txn.clear();
8151                 penalty_txn
8152         };
8153         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8154         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8155         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8156         {
8157                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8158                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8159                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8160         }
8161 }
8162
8163 #[test]
8164 fn test_pending_claimed_htlc_no_balance_underflow() {
8165         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8166         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8167         let chanmon_cfgs = create_chanmon_cfgs(2);
8168         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8169         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8170         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8171         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8172
8173         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8174         nodes[1].node.claim_funds(payment_preimage);
8175         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8176         check_added_monitors!(nodes[1], 1);
8177         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8178
8179         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8180         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8181         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8182         check_added_monitors!(nodes[0], 1);
8183         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8184
8185         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8186         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8187         // can get our balance.
8188
8189         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8190         // the public key of the only hop. This works around ChannelDetails not showing the
8191         // almost-claimed HTLC as available balance.
8192         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8193         route.payment_params = None; // This is all wrong, but unnecessary
8194         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8195         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8196         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8197
8198         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8199 }
8200
8201 #[test]
8202 fn test_channel_conf_timeout() {
8203         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8204         // confirm within 2016 blocks, as recommended by BOLT 2.
8205         let chanmon_cfgs = create_chanmon_cfgs(2);
8206         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8207         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8208         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8209
8210         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8211
8212         // The outbound node should wait forever for confirmation:
8213         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8214         // copied here instead of directly referencing the constant.
8215         connect_blocks(&nodes[0], 2016);
8216         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8217
8218         // The inbound node should fail the channel after exactly 2016 blocks
8219         connect_blocks(&nodes[1], 2015);
8220         check_added_monitors!(nodes[1], 0);
8221         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8222
8223         connect_blocks(&nodes[1], 1);
8224         check_added_monitors!(nodes[1], 1);
8225         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8226         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8227         assert_eq!(close_ev.len(), 1);
8228         match close_ev[0] {
8229                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8230                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8231                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8232                 },
8233                 _ => panic!("Unexpected event"),
8234         }
8235 }
8236
8237 #[test]
8238 fn test_override_channel_config() {
8239         let chanmon_cfgs = create_chanmon_cfgs(2);
8240         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8241         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8242         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8243
8244         // Node0 initiates a channel to node1 using the override config.
8245         let mut override_config = UserConfig::default();
8246         override_config.channel_handshake_config.our_to_self_delay = 200;
8247
8248         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8249
8250         // Assert the channel created by node0 is using the override config.
8251         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8252         assert_eq!(res.channel_flags, 0);
8253         assert_eq!(res.to_self_delay, 200);
8254 }
8255
8256 #[test]
8257 fn test_override_0msat_htlc_minimum() {
8258         let mut zero_config = UserConfig::default();
8259         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8260         let chanmon_cfgs = create_chanmon_cfgs(2);
8261         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8262         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8263         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8264
8265         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8266         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8267         assert_eq!(res.htlc_minimum_msat, 1);
8268
8269         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8270         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8271         assert_eq!(res.htlc_minimum_msat, 1);
8272 }
8273
8274 #[test]
8275 fn test_channel_update_has_correct_htlc_maximum_msat() {
8276         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8277         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8278         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8279         // 90% of the `channel_value`.
8280         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8281
8282         let mut config_30_percent = UserConfig::default();
8283         config_30_percent.channel_handshake_config.announced_channel = true;
8284         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8285         let mut config_50_percent = UserConfig::default();
8286         config_50_percent.channel_handshake_config.announced_channel = true;
8287         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8288         let mut config_95_percent = UserConfig::default();
8289         config_95_percent.channel_handshake_config.announced_channel = true;
8290         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8291         let mut config_100_percent = UserConfig::default();
8292         config_100_percent.channel_handshake_config.announced_channel = true;
8293         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8294
8295         let chanmon_cfgs = create_chanmon_cfgs(4);
8296         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8297         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)]);
8298         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8299
8300         let channel_value_satoshis = 100000;
8301         let channel_value_msat = channel_value_satoshis * 1000;
8302         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8303         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8304         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8305
8306         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());
8307         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());
8308
8309         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8310         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8311         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8312         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8313         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8314         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8315
8316         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8317         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8318         // `channel_value`.
8319         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8320         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8321         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8322         // `channel_value`.
8323         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8324 }
8325
8326 #[test]
8327 fn test_manually_accept_inbound_channel_request() {
8328         let mut manually_accept_conf = UserConfig::default();
8329         manually_accept_conf.manually_accept_inbound_channels = true;
8330         let chanmon_cfgs = create_chanmon_cfgs(2);
8331         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8332         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8333         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8334
8335         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8336         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8337
8338         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8339
8340         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8341         // accepting the inbound channel request.
8342         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8343
8344         let events = nodes[1].node.get_and_clear_pending_events();
8345         match events[0] {
8346                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8347                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8348                 }
8349                 _ => panic!("Unexpected event"),
8350         }
8351
8352         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8353         assert_eq!(accept_msg_ev.len(), 1);
8354
8355         match accept_msg_ev[0] {
8356                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8357                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8358                 }
8359                 _ => panic!("Unexpected event"),
8360         }
8361
8362         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8363
8364         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8365         assert_eq!(close_msg_ev.len(), 1);
8366
8367         let events = nodes[1].node.get_and_clear_pending_events();
8368         match events[0] {
8369                 Event::ChannelClosed { user_channel_id, .. } => {
8370                         assert_eq!(user_channel_id, 23);
8371                 }
8372                 _ => panic!("Unexpected event"),
8373         }
8374 }
8375
8376 #[test]
8377 fn test_manually_reject_inbound_channel_request() {
8378         let mut manually_accept_conf = UserConfig::default();
8379         manually_accept_conf.manually_accept_inbound_channels = true;
8380         let chanmon_cfgs = create_chanmon_cfgs(2);
8381         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8382         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8383         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8384
8385         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8386         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8387
8388         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8389
8390         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8391         // rejecting the inbound channel request.
8392         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8393
8394         let events = nodes[1].node.get_and_clear_pending_events();
8395         match events[0] {
8396                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8397                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8398                 }
8399                 _ => panic!("Unexpected event"),
8400         }
8401
8402         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8403         assert_eq!(close_msg_ev.len(), 1);
8404
8405         match close_msg_ev[0] {
8406                 MessageSendEvent::HandleError { ref node_id, .. } => {
8407                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8408                 }
8409                 _ => panic!("Unexpected event"),
8410         }
8411         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8412 }
8413
8414 #[test]
8415 fn test_reject_funding_before_inbound_channel_accepted() {
8416         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8417         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8418         // the node operator before the counterparty sends a `FundingCreated` message. If a
8419         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8420         // and the channel should be closed.
8421         let mut manually_accept_conf = UserConfig::default();
8422         manually_accept_conf.manually_accept_inbound_channels = true;
8423         let chanmon_cfgs = create_chanmon_cfgs(2);
8424         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8425         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8426         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8427
8428         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8429         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8430         let temp_channel_id = res.temporary_channel_id;
8431
8432         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8433
8434         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8435         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8436
8437         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8438         nodes[1].node.get_and_clear_pending_events();
8439
8440         // Get the `AcceptChannel` message of `nodes[1]` without calling
8441         // `ChannelManager::accept_inbound_channel`, which generates a
8442         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8443         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8444         // succeed when `nodes[0]` is passed to it.
8445         {
8446                 let mut lock;
8447                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8448                 let accept_chan_msg = channel.get_accept_channel_message();
8449                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8450         }
8451
8452         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8453
8454         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8455         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8456
8457         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8458         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8459
8460         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8461         assert_eq!(close_msg_ev.len(), 1);
8462
8463         let expected_err = "FundingCreated message received before the channel was accepted";
8464         match close_msg_ev[0] {
8465                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8466                         assert_eq!(msg.channel_id, temp_channel_id);
8467                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8468                         assert_eq!(msg.data, expected_err);
8469                 }
8470                 _ => panic!("Unexpected event"),
8471         }
8472
8473         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8474 }
8475
8476 #[test]
8477 fn test_can_not_accept_inbound_channel_twice() {
8478         let mut manually_accept_conf = UserConfig::default();
8479         manually_accept_conf.manually_accept_inbound_channels = true;
8480         let chanmon_cfgs = create_chanmon_cfgs(2);
8481         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8482         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8483         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8484
8485         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8486         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8487
8488         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8489
8490         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8491         // accepting the inbound channel request.
8492         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8493
8494         let events = nodes[1].node.get_and_clear_pending_events();
8495         match events[0] {
8496                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8497                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8498                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8499                         match api_res {
8500                                 Err(APIError::APIMisuseError { err }) => {
8501                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8502                                 },
8503                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8504                                 Err(_) => panic!("Unexpected Error"),
8505                         }
8506                 }
8507                 _ => panic!("Unexpected event"),
8508         }
8509
8510         // Ensure that the channel wasn't closed after attempting to accept it twice.
8511         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8512         assert_eq!(accept_msg_ev.len(), 1);
8513
8514         match accept_msg_ev[0] {
8515                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8516                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8517                 }
8518                 _ => panic!("Unexpected event"),
8519         }
8520 }
8521
8522 #[test]
8523 fn test_can_not_accept_unknown_inbound_channel() {
8524         let chanmon_cfg = create_chanmon_cfgs(2);
8525         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8526         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8527         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8528
8529         let unknown_channel_id = [0; 32];
8530         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8531         match api_res {
8532                 Err(APIError::ChannelUnavailable { err }) => {
8533                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8534                 },
8535                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8536                 Err(_) => panic!("Unexpected Error"),
8537         }
8538 }
8539
8540 #[test]
8541 fn test_simple_mpp() {
8542         // Simple test of sending a multi-path payment.
8543         let chanmon_cfgs = create_chanmon_cfgs(4);
8544         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8545         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8546         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8547
8548         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8549         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8550         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8551         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8552
8553         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8554         let path = route.paths[0].clone();
8555         route.paths.push(path);
8556         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8557         route.paths[0][0].short_channel_id = chan_1_id;
8558         route.paths[0][1].short_channel_id = chan_3_id;
8559         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8560         route.paths[1][0].short_channel_id = chan_2_id;
8561         route.paths[1][1].short_channel_id = chan_4_id;
8562         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8563         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8564 }
8565
8566 #[test]
8567 fn test_preimage_storage() {
8568         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8569         let chanmon_cfgs = create_chanmon_cfgs(2);
8570         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8571         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8572         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8573
8574         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8575
8576         {
8577                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8578                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8579                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8580                 check_added_monitors!(nodes[0], 1);
8581                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8582                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8583                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8584                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8585         }
8586         // Note that after leaving the above scope we have no knowledge of any arguments or return
8587         // values from previous calls.
8588         expect_pending_htlcs_forwardable!(nodes[1]);
8589         let events = nodes[1].node.get_and_clear_pending_events();
8590         assert_eq!(events.len(), 1);
8591         match events[0] {
8592                 Event::PaymentReceived { ref purpose, .. } => {
8593                         match &purpose {
8594                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8595                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8596                                 },
8597                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8598                         }
8599                 },
8600                 _ => panic!("Unexpected event"),
8601         }
8602 }
8603
8604 #[test]
8605 #[allow(deprecated)]
8606 fn test_secret_timeout() {
8607         // Simple test of payment secret storage time outs. After
8608         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8609         let chanmon_cfgs = create_chanmon_cfgs(2);
8610         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8611         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8612         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8613
8614         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8615
8616         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8617
8618         // We should fail to register the same payment hash twice, at least until we've connected a
8619         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8620         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8621                 assert_eq!(err, "Duplicate payment hash");
8622         } else { panic!(); }
8623         let mut block = {
8624                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8625                 Block {
8626                         header: BlockHeader {
8627                                 version: 0x2000000,
8628                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8629                                 merkle_root: Default::default(),
8630                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8631                         txdata: vec![],
8632                 }
8633         };
8634         connect_block(&nodes[1], &block);
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
8639         // If we then connect the second block, we should be able to register the same payment hash
8640         // again (this time getting a new payment secret).
8641         block.header.prev_blockhash = block.header.block_hash();
8642         block.header.time += 1;
8643         connect_block(&nodes[1], &block);
8644         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8645         assert_ne!(payment_secret_1, our_payment_secret);
8646
8647         {
8648                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8649                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8650                 check_added_monitors!(nodes[0], 1);
8651                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8652                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8653                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8654                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8655         }
8656         // Note that after leaving the above scope we have no knowledge of any arguments or return
8657         // values from previous calls.
8658         expect_pending_htlcs_forwardable!(nodes[1]);
8659         let events = nodes[1].node.get_and_clear_pending_events();
8660         assert_eq!(events.len(), 1);
8661         match events[0] {
8662                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8663                         assert!(payment_preimage.is_none());
8664                         assert_eq!(payment_secret, our_payment_secret);
8665                         // We don't actually have the payment preimage with which to claim this payment!
8666                 },
8667                 _ => panic!("Unexpected event"),
8668         }
8669 }
8670
8671 #[test]
8672 fn test_bad_secret_hash() {
8673         // Simple test of unregistered payment hash/invalid payment secret handling
8674         let chanmon_cfgs = create_chanmon_cfgs(2);
8675         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8676         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8677         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8678
8679         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8680
8681         let random_payment_hash = PaymentHash([42; 32]);
8682         let random_payment_secret = PaymentSecret([43; 32]);
8683         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8684         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8685
8686         // All the below cases should end up being handled exactly identically, so we macro the
8687         // resulting events.
8688         macro_rules! handle_unknown_invalid_payment_data {
8689                 () => {
8690                         check_added_monitors!(nodes[0], 1);
8691                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8692                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8693                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8694                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8695
8696                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8697                         // again to process the pending backwards-failure of the HTLC
8698                         expect_pending_htlcs_forwardable!(nodes[1]);
8699                         expect_pending_htlcs_forwardable!(nodes[1]);
8700                         check_added_monitors!(nodes[1], 1);
8701
8702                         // We should fail the payment back
8703                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8704                         match events.pop().unwrap() {
8705                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8706                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8707                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8708                                 },
8709                                 _ => panic!("Unexpected event"),
8710                         }
8711                 }
8712         }
8713
8714         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8715         // Error data is the HTLC value (100,000) and current block height
8716         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8717
8718         // Send a payment with the right payment hash but the wrong payment secret
8719         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8720         handle_unknown_invalid_payment_data!();
8721         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8722
8723         // Send a payment with a random payment hash, but the right payment secret
8724         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8725         handle_unknown_invalid_payment_data!();
8726         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8727
8728         // Send a payment with a random payment hash and random payment secret
8729         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8730         handle_unknown_invalid_payment_data!();
8731         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8732 }
8733
8734 #[test]
8735 fn test_update_err_monitor_lockdown() {
8736         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8737         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8738         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8739         //
8740         // This scenario may happen in a watchtower setup, where watchtower process a block height
8741         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8742         // commitment at same time.
8743
8744         let chanmon_cfgs = create_chanmon_cfgs(2);
8745         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8746         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8747         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8748
8749         // Create some initial channel
8750         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8751         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8752
8753         // Rebalance the network to generate htlc in the two directions
8754         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8755
8756         // Route a HTLC from node 0 to node 1 (but don't settle)
8757         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8758
8759         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8760         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8761         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8762         let persister = test_utils::TestPersister::new();
8763         let watchtower = {
8764                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8765                 let mut w = test_utils::TestVecWriter(Vec::new());
8766                 monitor.write(&mut w).unwrap();
8767                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8768                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8769                 assert!(new_monitor == *monitor);
8770                 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);
8771                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8772                 watchtower
8773         };
8774         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8775         let block = Block { header, txdata: vec![] };
8776         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8777         // transaction lock time requirements here.
8778         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8779         watchtower.chain_monitor.block_connected(&block, 200);
8780
8781         // Try to update ChannelMonitor
8782         nodes[1].node.claim_funds(preimage);
8783         check_added_monitors!(nodes[1], 1);
8784         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8785
8786         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8787         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8788         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8789         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8790                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8791                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8792                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8793                 } else { assert!(false); }
8794         } else { assert!(false); };
8795         // Our local monitor is in-sync and hasn't processed yet timeout
8796         check_added_monitors!(nodes[0], 1);
8797         let events = nodes[0].node.get_and_clear_pending_events();
8798         assert_eq!(events.len(), 1);
8799 }
8800
8801 #[test]
8802 fn test_concurrent_monitor_claim() {
8803         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8804         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8805         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8806         // state N+1 confirms. Alice claims output from state N+1.
8807
8808         let chanmon_cfgs = create_chanmon_cfgs(2);
8809         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8810         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8811         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8812
8813         // Create some initial channel
8814         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8815         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8816
8817         // Rebalance the network to generate htlc in the two directions
8818         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8819
8820         // Route a HTLC from node 0 to node 1 (but don't settle)
8821         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8822
8823         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8824         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8825         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8826         let persister = test_utils::TestPersister::new();
8827         let watchtower_alice = {
8828                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8829                 let mut w = test_utils::TestVecWriter(Vec::new());
8830                 monitor.write(&mut w).unwrap();
8831                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8832                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8833                 assert!(new_monitor == *monitor);
8834                 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);
8835                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8836                 watchtower
8837         };
8838         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8839         let block = Block { header, txdata: vec![] };
8840         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8841         // transaction lock time requirements here.
8842         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));
8843         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8844
8845         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8846         {
8847                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8848                 assert_eq!(txn.len(), 2);
8849                 txn.clear();
8850         }
8851
8852         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8853         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8854         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8855         let persister = test_utils::TestPersister::new();
8856         let watchtower_bob = {
8857                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8858                 let mut w = test_utils::TestVecWriter(Vec::new());
8859                 monitor.write(&mut w).unwrap();
8860                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8861                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8862                 assert!(new_monitor == *monitor);
8863                 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);
8864                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8865                 watchtower
8866         };
8867         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8868         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8869
8870         // Route another payment to generate another update with still previous HTLC pending
8871         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8872         {
8873                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8874         }
8875         check_added_monitors!(nodes[1], 1);
8876
8877         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8878         assert_eq!(updates.update_add_htlcs.len(), 1);
8879         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8880         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8881                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8882                         // Watchtower Alice should already have seen the block and reject the update
8883                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8884                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8885                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8886                 } else { assert!(false); }
8887         } else { assert!(false); };
8888         // Our local monitor is in-sync and hasn't processed yet timeout
8889         check_added_monitors!(nodes[0], 1);
8890
8891         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8892         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8893         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8894
8895         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8896         let bob_state_y;
8897         {
8898                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8899                 assert_eq!(txn.len(), 2);
8900                 bob_state_y = txn[0].clone();
8901                 txn.clear();
8902         };
8903
8904         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8905         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8906         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);
8907         {
8908                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8909                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8910                 // the onchain detection of the HTLC output
8911                 assert_eq!(htlc_txn.len(), 2);
8912                 check_spends!(htlc_txn[0], bob_state_y);
8913                 check_spends!(htlc_txn[1], bob_state_y);
8914         }
8915 }
8916
8917 #[test]
8918 fn test_pre_lockin_no_chan_closed_update() {
8919         // Test that if a peer closes a channel in response to a funding_created message we don't
8920         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8921         // message).
8922         //
8923         // Doing so would imply a channel monitor update before the initial channel monitor
8924         // registration, violating our API guarantees.
8925         //
8926         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8927         // then opening a second channel with the same funding output as the first (which is not
8928         // rejected because the first channel does not exist in the ChannelManager) and closing it
8929         // before receiving funding_signed.
8930         let chanmon_cfgs = create_chanmon_cfgs(2);
8931         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8932         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8933         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8934
8935         // Create an initial channel
8936         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8937         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8938         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8939         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8940         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8941
8942         // Move the first channel through the funding flow...
8943         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8944
8945         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8946         check_added_monitors!(nodes[0], 0);
8947
8948         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8949         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8950         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8951         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8952         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8953 }
8954
8955 #[test]
8956 fn test_htlc_no_detection() {
8957         // This test is a mutation to underscore the detection logic bug we had
8958         // before #653. HTLC value routed is above the remaining balance, thus
8959         // inverting HTLC and `to_remote` output. HTLC will come second and
8960         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8961         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8962         // outputs order detection for correct spending children filtring.
8963
8964         let chanmon_cfgs = create_chanmon_cfgs(2);
8965         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8966         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8967         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8968
8969         // Create some initial channels
8970         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8971
8972         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8973         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8974         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8975         assert_eq!(local_txn[0].input.len(), 1);
8976         assert_eq!(local_txn[0].output.len(), 3);
8977         check_spends!(local_txn[0], chan_1.3);
8978
8979         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8980         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8981         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8982         // We deliberately connect the local tx twice as this should provoke a failure calling
8983         // this test before #653 fix.
8984         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);
8985         check_closed_broadcast!(nodes[0], true);
8986         check_added_monitors!(nodes[0], 1);
8987         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8988         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8989
8990         let htlc_timeout = {
8991                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8992                 assert_eq!(node_txn[1].input.len(), 1);
8993                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8994                 check_spends!(node_txn[1], local_txn[0]);
8995                 node_txn[1].clone()
8996         };
8997
8998         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8999         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9000         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9001         expect_payment_failed!(nodes[0], our_payment_hash, true);
9002 }
9003
9004 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9005         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9006         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9007         // Carol, Alice would be the upstream node, and Carol the downstream.)
9008         //
9009         // Steps of the test:
9010         // 1) Alice sends a HTLC to Carol through Bob.
9011         // 2) Carol doesn't settle the HTLC.
9012         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9013         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9014         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9015         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9016         // 5) Carol release the preimage to Bob off-chain.
9017         // 6) Bob claims the offered output on the broadcasted commitment.
9018         let chanmon_cfgs = create_chanmon_cfgs(3);
9019         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9020         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9021         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9022
9023         // Create some initial channels
9024         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9025         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9026
9027         // Steps (1) and (2):
9028         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9029         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9030
9031         // Check that Alice's commitment transaction now contains an output for this HTLC.
9032         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9033         check_spends!(alice_txn[0], chan_ab.3);
9034         assert_eq!(alice_txn[0].output.len(), 2);
9035         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9036         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9037         assert_eq!(alice_txn.len(), 2);
9038
9039         // Steps (3) and (4):
9040         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9041         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9042         let mut force_closing_node = 0; // Alice force-closes
9043         let mut counterparty_node = 1; // Bob if Alice force-closes
9044
9045         // Bob force-closes
9046         if !broadcast_alice {
9047                 force_closing_node = 1;
9048                 counterparty_node = 0;
9049         }
9050         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9051         check_closed_broadcast!(nodes[force_closing_node], true);
9052         check_added_monitors!(nodes[force_closing_node], 1);
9053         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9054         if go_onchain_before_fulfill {
9055                 let txn_to_broadcast = match broadcast_alice {
9056                         true => alice_txn.clone(),
9057                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9058                 };
9059                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9060                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9061                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9062                 if broadcast_alice {
9063                         check_closed_broadcast!(nodes[1], true);
9064                         check_added_monitors!(nodes[1], 1);
9065                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9066                 }
9067                 assert_eq!(bob_txn.len(), 1);
9068                 check_spends!(bob_txn[0], chan_ab.3);
9069         }
9070
9071         // Step (5):
9072         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9073         // process of removing the HTLC from their commitment transactions.
9074         nodes[2].node.claim_funds(payment_preimage);
9075         check_added_monitors!(nodes[2], 1);
9076         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9077
9078         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9079         assert!(carol_updates.update_add_htlcs.is_empty());
9080         assert!(carol_updates.update_fail_htlcs.is_empty());
9081         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9082         assert!(carol_updates.update_fee.is_none());
9083         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9084
9085         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9086         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9087         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9088         if !go_onchain_before_fulfill && broadcast_alice {
9089                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9090                 assert_eq!(events.len(), 1);
9091                 match events[0] {
9092                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9093                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9094                         },
9095                         _ => panic!("Unexpected event"),
9096                 };
9097         }
9098         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9099         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9100         // Carol<->Bob's updated commitment transaction info.
9101         check_added_monitors!(nodes[1], 2);
9102
9103         let events = nodes[1].node.get_and_clear_pending_msg_events();
9104         assert_eq!(events.len(), 2);
9105         let bob_revocation = match events[0] {
9106                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9107                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9108                         (*msg).clone()
9109                 },
9110                 _ => panic!("Unexpected event"),
9111         };
9112         let bob_updates = match events[1] {
9113                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9114                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9115                         (*updates).clone()
9116                 },
9117                 _ => panic!("Unexpected event"),
9118         };
9119
9120         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9121         check_added_monitors!(nodes[2], 1);
9122         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9123         check_added_monitors!(nodes[2], 1);
9124
9125         let events = nodes[2].node.get_and_clear_pending_msg_events();
9126         assert_eq!(events.len(), 1);
9127         let carol_revocation = match events[0] {
9128                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9129                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9130                         (*msg).clone()
9131                 },
9132                 _ => panic!("Unexpected event"),
9133         };
9134         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9135         check_added_monitors!(nodes[1], 1);
9136
9137         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9138         // here's where we put said channel's commitment tx on-chain.
9139         let mut txn_to_broadcast = alice_txn.clone();
9140         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9141         if !go_onchain_before_fulfill {
9142                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9143                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9144                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9145                 if broadcast_alice {
9146                         check_closed_broadcast!(nodes[1], true);
9147                         check_added_monitors!(nodes[1], 1);
9148                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9149                 }
9150                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9151                 if broadcast_alice {
9152                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9153                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9154                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9155                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9156                         // broadcasted.
9157                         assert_eq!(bob_txn.len(), 3);
9158                         check_spends!(bob_txn[1], chan_ab.3);
9159                 } else {
9160                         assert_eq!(bob_txn.len(), 2);
9161                         check_spends!(bob_txn[0], chan_ab.3);
9162                 }
9163         }
9164
9165         // Step (6):
9166         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9167         // broadcasted commitment transaction.
9168         {
9169                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9170                 if go_onchain_before_fulfill {
9171                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9172                         assert_eq!(bob_txn.len(), 2);
9173                 }
9174                 let script_weight = match broadcast_alice {
9175                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9176                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9177                 };
9178                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9179                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9180                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9181                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9182                 if broadcast_alice && !go_onchain_before_fulfill {
9183                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9184                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9185                 } else {
9186                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9187                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9188                 }
9189         }
9190 }
9191
9192 #[test]
9193 fn test_onchain_htlc_settlement_after_close() {
9194         do_test_onchain_htlc_settlement_after_close(true, true);
9195         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9196         do_test_onchain_htlc_settlement_after_close(true, false);
9197         do_test_onchain_htlc_settlement_after_close(false, false);
9198 }
9199
9200 #[test]
9201 fn test_duplicate_chan_id() {
9202         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9203         // already open we reject it and keep the old channel.
9204         //
9205         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9206         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9207         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9208         // updating logic for the existing channel.
9209         let chanmon_cfgs = create_chanmon_cfgs(2);
9210         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9211         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9212         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9213
9214         // Create an initial channel
9215         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9216         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9217         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9218         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()));
9219
9220         // Try to create a second channel with the same temporary_channel_id as the first and check
9221         // that it is rejected.
9222         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9223         {
9224                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9225                 assert_eq!(events.len(), 1);
9226                 match events[0] {
9227                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9228                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9229                                 // first (valid) and second (invalid) channels are closed, given they both have
9230                                 // the same non-temporary channel_id. However, currently we do not, so we just
9231                                 // move forward with it.
9232                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9233                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9234                         },
9235                         _ => panic!("Unexpected event"),
9236                 }
9237         }
9238
9239         // Move the first channel through the funding flow...
9240         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9241
9242         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9243         check_added_monitors!(nodes[0], 0);
9244
9245         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9246         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9247         {
9248                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9249                 assert_eq!(added_monitors.len(), 1);
9250                 assert_eq!(added_monitors[0].0, funding_output);
9251                 added_monitors.clear();
9252         }
9253         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9254
9255         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9256         let channel_id = funding_outpoint.to_channel_id();
9257
9258         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9259         // temporary one).
9260
9261         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9262         // Technically this is allowed by the spec, but we don't support it and there's little reason
9263         // to. Still, it shouldn't cause any other issues.
9264         open_chan_msg.temporary_channel_id = channel_id;
9265         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9266         {
9267                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9268                 assert_eq!(events.len(), 1);
9269                 match events[0] {
9270                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9271                                 // Technically, at this point, nodes[1] would be justified in thinking both
9272                                 // channels are closed, but currently we do not, so we just move forward with it.
9273                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9274                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9275                         },
9276                         _ => panic!("Unexpected event"),
9277                 }
9278         }
9279
9280         // Now try to create a second channel which has a duplicate funding output.
9281         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9282         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9283         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9284         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()));
9285         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9286
9287         let funding_created = {
9288                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9289                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9290                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9291                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9292                 // channelmanager in a possibly nonsense state instead).
9293                 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9294                 let logger = test_utils::TestLogger::new();
9295                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9296         };
9297         check_added_monitors!(nodes[0], 0);
9298         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9299         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9300         // still needs to be cleared here.
9301         check_added_monitors!(nodes[1], 1);
9302
9303         // ...still, nodes[1] will reject the duplicate channel.
9304         {
9305                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9306                 assert_eq!(events.len(), 1);
9307                 match events[0] {
9308                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9309                                 // Technically, at this point, nodes[1] would be justified in thinking both
9310                                 // channels are closed, but currently we do not, so we just move forward with it.
9311                                 assert_eq!(msg.channel_id, channel_id);
9312                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9313                         },
9314                         _ => panic!("Unexpected event"),
9315                 }
9316         }
9317
9318         // finally, finish creating the original channel and send a payment over it to make sure
9319         // everything is functional.
9320         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9321         {
9322                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9323                 assert_eq!(added_monitors.len(), 1);
9324                 assert_eq!(added_monitors[0].0, funding_output);
9325                 added_monitors.clear();
9326         }
9327
9328         let events_4 = nodes[0].node.get_and_clear_pending_events();
9329         assert_eq!(events_4.len(), 0);
9330         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9331         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9332
9333         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9334         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9335         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9336         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9337 }
9338
9339 #[test]
9340 fn test_error_chans_closed() {
9341         // Test that we properly handle error messages, closing appropriate channels.
9342         //
9343         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9344         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9345         // we can test various edge cases around it to ensure we don't regress.
9346         let chanmon_cfgs = create_chanmon_cfgs(3);
9347         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9348         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9349         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9350
9351         // Create some initial channels
9352         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9353         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9354         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9355
9356         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9357         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9358         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9359
9360         // Closing a channel from a different peer has no effect
9361         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9362         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9363
9364         // Closing one channel doesn't impact others
9365         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9366         check_added_monitors!(nodes[0], 1);
9367         check_closed_broadcast!(nodes[0], false);
9368         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9369         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9370         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9371         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);
9372         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);
9373
9374         // A null channel ID should close all channels
9375         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9376         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9377         check_added_monitors!(nodes[0], 2);
9378         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9379         let events = nodes[0].node.get_and_clear_pending_msg_events();
9380         assert_eq!(events.len(), 2);
9381         match events[0] {
9382                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9383                         assert_eq!(msg.contents.flags & 2, 2);
9384                 },
9385                 _ => panic!("Unexpected event"),
9386         }
9387         match events[1] {
9388                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9389                         assert_eq!(msg.contents.flags & 2, 2);
9390                 },
9391                 _ => panic!("Unexpected event"),
9392         }
9393         // Note that at this point users of a standard PeerHandler will end up calling
9394         // peer_disconnected with no_connection_possible set to false, duplicating the
9395         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9396         // users with their own peer handling logic. We duplicate the call here, however.
9397         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9398         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9399
9400         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9401         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9402         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9403 }
9404
9405 #[test]
9406 fn test_invalid_funding_tx() {
9407         // Test that we properly handle invalid funding transactions sent to us from a peer.
9408         //
9409         // Previously, all other major lightning implementations had failed to properly sanitize
9410         // funding transactions from their counterparties, leading to a multi-implementation critical
9411         // security vulnerability (though we always sanitized properly, we've previously had
9412         // un-released crashes in the sanitization process).
9413         //
9414         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9415         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9416         // gave up on it. We test this here by generating such a transaction.
9417         let chanmon_cfgs = create_chanmon_cfgs(2);
9418         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9419         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9420         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9421
9422         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9423         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()));
9424         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()));
9425
9426         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9427
9428         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9429         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9430         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9431         // its length.
9432         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9433         assert!(chan_utils::HTLCType::scriptlen_to_htlctype(wit_program.len()).unwrap() ==
9434                 chan_utils::HTLCType::AcceptedHTLC);
9435
9436         let wit_program_script: Script = wit_program.clone().into();
9437         for output in tx.output.iter_mut() {
9438                 // Make the confirmed funding transaction have a bogus script_pubkey
9439                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9440         }
9441
9442         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9443         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()));
9444         check_added_monitors!(nodes[1], 1);
9445
9446         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()));
9447         check_added_monitors!(nodes[0], 1);
9448
9449         let events_1 = nodes[0].node.get_and_clear_pending_events();
9450         assert_eq!(events_1.len(), 0);
9451
9452         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9453         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9454         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9455
9456         let expected_err = "funding tx had wrong script/value or output index";
9457         confirm_transaction_at(&nodes[1], &tx, 1);
9458         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9459         check_added_monitors!(nodes[1], 1);
9460         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9461         assert_eq!(events_2.len(), 1);
9462         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9463                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9464                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9465                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9466                 } else { panic!(); }
9467         } else { panic!(); }
9468         assert_eq!(nodes[1].node.list_channels().len(), 0);
9469
9470         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9471         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9472         // as its not 32 bytes long.
9473         let mut spend_tx = Transaction {
9474                 version: 2i32, lock_time: 0,
9475                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9476                         previous_output: BitcoinOutPoint {
9477                                 txid: tx.txid(),
9478                                 vout: idx as u32,
9479                         },
9480                         script_sig: Script::new(),
9481                         sequence: 0xfffffffd,
9482                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9483                 }).collect(),
9484                 output: vec![TxOut {
9485                         value: 1000,
9486                         script_pubkey: Script::new(),
9487                 }]
9488         };
9489         check_spends!(spend_tx, tx);
9490         mine_transaction(&nodes[1], &spend_tx);
9491 }
9492
9493 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9494         // In the first version of the chain::Confirm interface, after a refactor was made to not
9495         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9496         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9497         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9498         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9499         // spending transaction until height N+1 (or greater). This was due to the way
9500         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9501         // spending transaction at the height the input transaction was confirmed at, not whether we
9502         // should broadcast a spending transaction at the current height.
9503         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9504         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9505         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9506         // until we learned about an additional block.
9507         //
9508         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9509         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9510         let chanmon_cfgs = create_chanmon_cfgs(3);
9511         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9512         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9513         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9514         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9515
9516         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9517         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9518         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9519         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9520         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9521
9522         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9523         check_closed_broadcast!(nodes[1], true);
9524         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9525         check_added_monitors!(nodes[1], 1);
9526         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9527         assert_eq!(node_txn.len(), 1);
9528
9529         let conf_height = nodes[1].best_block_info().1;
9530         if !test_height_before_timelock {
9531                 connect_blocks(&nodes[1], 24 * 6);
9532         }
9533         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9534                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9535         if test_height_before_timelock {
9536                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9537                 // generate any events or broadcast any transactions
9538                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9539                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9540         } else {
9541                 // We should broadcast an HTLC transaction spending our funding transaction first
9542                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9543                 assert_eq!(spending_txn.len(), 2);
9544                 assert_eq!(spending_txn[0], node_txn[0]);
9545                 check_spends!(spending_txn[1], node_txn[0]);
9546                 // We should also generate a SpendableOutputs event with the to_self output (as its
9547                 // timelock is up).
9548                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9549                 assert_eq!(descriptor_spend_txn.len(), 1);
9550
9551                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9552                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9553                 // additional block built on top of the current chain.
9554                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9555                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9556                 expect_pending_htlcs_forwardable!(nodes[1]);
9557                 check_added_monitors!(nodes[1], 1);
9558
9559                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9560                 assert!(updates.update_add_htlcs.is_empty());
9561                 assert!(updates.update_fulfill_htlcs.is_empty());
9562                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9563                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9564                 assert!(updates.update_fee.is_none());
9565                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9566                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9567                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9568         }
9569 }
9570
9571 #[test]
9572 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9573         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9574         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9575 }
9576
9577 #[test]
9578 fn test_forwardable_regen() {
9579         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9580         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9581         // HTLCs.
9582         // We test it for both payment receipt and payment forwarding.
9583
9584         let chanmon_cfgs = create_chanmon_cfgs(3);
9585         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9586         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9587         let persister: test_utils::TestPersister;
9588         let new_chain_monitor: test_utils::TestChainMonitor;
9589         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9590         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9591         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9592         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9593
9594         // First send a payment to nodes[1]
9595         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9596         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9597         check_added_monitors!(nodes[0], 1);
9598
9599         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9600         assert_eq!(events.len(), 1);
9601         let payment_event = SendEvent::from_event(events.pop().unwrap());
9602         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9603         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9604
9605         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9606
9607         // Next send a payment which is forwarded by nodes[1]
9608         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9609         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9610         check_added_monitors!(nodes[0], 1);
9611
9612         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9613         assert_eq!(events.len(), 1);
9614         let payment_event = SendEvent::from_event(events.pop().unwrap());
9615         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9616         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9617
9618         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9619         // generated
9620         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9621
9622         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9623         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9624         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9625
9626         let nodes_1_serialized = nodes[1].node.encode();
9627         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9628         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9629         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9630         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9631
9632         persister = test_utils::TestPersister::new();
9633         let keys_manager = &chanmon_cfgs[1].keys_manager;
9634         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);
9635         nodes[1].chain_monitor = &new_chain_monitor;
9636
9637         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9638         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9639                 &mut chan_0_monitor_read, keys_manager).unwrap();
9640         assert!(chan_0_monitor_read.is_empty());
9641         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9642         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9643                 &mut chan_1_monitor_read, keys_manager).unwrap();
9644         assert!(chan_1_monitor_read.is_empty());
9645
9646         let mut nodes_1_read = &nodes_1_serialized[..];
9647         let (_, nodes_1_deserialized_tmp) = {
9648                 let mut channel_monitors = HashMap::new();
9649                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9650                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9651                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9652                         default_config: UserConfig::default(),
9653                         keys_manager,
9654                         fee_estimator: node_cfgs[1].fee_estimator,
9655                         chain_monitor: nodes[1].chain_monitor,
9656                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9657                         logger: nodes[1].logger,
9658                         channel_monitors,
9659                 }).unwrap()
9660         };
9661         nodes_1_deserialized = nodes_1_deserialized_tmp;
9662         assert!(nodes_1_read.is_empty());
9663
9664         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9665         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9666         nodes[1].node = &nodes_1_deserialized;
9667         check_added_monitors!(nodes[1], 2);
9668
9669         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9670         // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9671         // the commitment state.
9672         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9673
9674         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9675
9676         expect_pending_htlcs_forwardable!(nodes[1]);
9677         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9678         check_added_monitors!(nodes[1], 1);
9679
9680         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9681         assert_eq!(events.len(), 1);
9682         let payment_event = SendEvent::from_event(events.pop().unwrap());
9683         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9684         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9685         expect_pending_htlcs_forwardable!(nodes[2]);
9686         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9687
9688         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9689         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9690 }
9691
9692 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9693         let chanmon_cfgs = create_chanmon_cfgs(2);
9694         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9695         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9696         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9697
9698         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9699
9700         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9701                 .with_features(InvoiceFeatures::known());
9702         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9703
9704         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9705
9706         {
9707                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9708                 check_added_monitors!(nodes[0], 1);
9709                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9710                 assert_eq!(events.len(), 1);
9711                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9712                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9713                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9714         }
9715         expect_pending_htlcs_forwardable!(nodes[1]);
9716         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9717
9718         {
9719                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9720                 check_added_monitors!(nodes[0], 1);
9721                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9722                 assert_eq!(events.len(), 1);
9723                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9724                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9725                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9726                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9727                 // assume the second is a privacy attack (no longer particularly relevant
9728                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9729                 // the first HTLC delivered above.
9730         }
9731
9732         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9733         nodes[1].node.process_pending_htlc_forwards();
9734
9735         if test_for_second_fail_panic {
9736                 // Now we go fail back the first HTLC from the user end.
9737                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9738
9739                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9740                 nodes[1].node.process_pending_htlc_forwards();
9741
9742                 check_added_monitors!(nodes[1], 1);
9743                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9744                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9745
9746                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9747                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9748                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9749
9750                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9751                 assert_eq!(failure_events.len(), 2);
9752                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9753                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9754         } else {
9755                 // Let the second HTLC fail and claim the first
9756                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9757                 nodes[1].node.process_pending_htlc_forwards();
9758
9759                 check_added_monitors!(nodes[1], 1);
9760                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9761                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9762                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9763
9764                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9765
9766                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9767         }
9768 }
9769
9770 #[test]
9771 fn test_dup_htlc_second_fail_panic() {
9772         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9773         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9774         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9775         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9776         do_test_dup_htlc_second_rejected(true);
9777 }
9778
9779 #[test]
9780 fn test_dup_htlc_second_rejected() {
9781         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9782         // simply reject the second HTLC but are still able to claim the first HTLC.
9783         do_test_dup_htlc_second_rejected(false);
9784 }
9785
9786 #[test]
9787 fn test_inconsistent_mpp_params() {
9788         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9789         // such HTLC and allow the second to stay.
9790         let chanmon_cfgs = create_chanmon_cfgs(4);
9791         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9792         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9793         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9794
9795         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9796         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9797         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9798         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9799
9800         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9801                 .with_features(InvoiceFeatures::known());
9802         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9803         assert_eq!(route.paths.len(), 2);
9804         route.paths.sort_by(|path_a, _| {
9805                 // Sort the path so that the path through nodes[1] comes first
9806                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9807                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9808         });
9809         let payment_params_opt = Some(payment_params);
9810
9811         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9812
9813         let cur_height = nodes[0].best_block_info().1;
9814         let payment_id = PaymentId([42; 32]);
9815         {
9816                 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();
9817                 check_added_monitors!(nodes[0], 1);
9818
9819                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9820                 assert_eq!(events.len(), 1);
9821                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9822         }
9823         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9824
9825         {
9826                 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();
9827                 check_added_monitors!(nodes[0], 1);
9828
9829                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9830                 assert_eq!(events.len(), 1);
9831                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9832
9833                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9834                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9835
9836                 expect_pending_htlcs_forwardable!(nodes[2]);
9837                 check_added_monitors!(nodes[2], 1);
9838
9839                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9840                 assert_eq!(events.len(), 1);
9841                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9842
9843                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9844                 check_added_monitors!(nodes[3], 0);
9845                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9846
9847                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9848                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9849                 // post-payment_secrets) and fail back the new HTLC.
9850         }
9851         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9852         nodes[3].node.process_pending_htlc_forwards();
9853         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9854         nodes[3].node.process_pending_htlc_forwards();
9855
9856         check_added_monitors!(nodes[3], 1);
9857
9858         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9859         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9860         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9861
9862         expect_pending_htlcs_forwardable!(nodes[2]);
9863         check_added_monitors!(nodes[2], 1);
9864
9865         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9866         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9867         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9868
9869         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9870
9871         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();
9872         check_added_monitors!(nodes[0], 1);
9873
9874         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9875         assert_eq!(events.len(), 1);
9876         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9877
9878         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9879 }
9880
9881 #[test]
9882 fn test_keysend_payments_to_public_node() {
9883         let chanmon_cfgs = create_chanmon_cfgs(2);
9884         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9885         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9886         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9887
9888         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9889         let network_graph = nodes[0].network_graph;
9890         let payer_pubkey = nodes[0].node.get_our_node_id();
9891         let payee_pubkey = nodes[1].node.get_our_node_id();
9892         let route_params = RouteParameters {
9893                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9894                 final_value_msat: 10000,
9895                 final_cltv_expiry_delta: 40,
9896         };
9897         let scorer = test_utils::TestScorer::with_penalty(0);
9898         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9899         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9900
9901         let test_preimage = PaymentPreimage([42; 32]);
9902         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9903         check_added_monitors!(nodes[0], 1);
9904         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9905         assert_eq!(events.len(), 1);
9906         let event = events.pop().unwrap();
9907         let path = vec![&nodes[1]];
9908         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9909         claim_payment(&nodes[0], &path, test_preimage);
9910 }
9911
9912 #[test]
9913 fn test_keysend_payments_to_private_node() {
9914         let chanmon_cfgs = create_chanmon_cfgs(2);
9915         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9916         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9917         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9918
9919         let payer_pubkey = nodes[0].node.get_our_node_id();
9920         let payee_pubkey = nodes[1].node.get_our_node_id();
9921         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9922         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9923
9924         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9925         let route_params = RouteParameters {
9926                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9927                 final_value_msat: 10000,
9928                 final_cltv_expiry_delta: 40,
9929         };
9930         let network_graph = nodes[0].network_graph;
9931         let first_hops = nodes[0].node.list_usable_channels();
9932         let scorer = test_utils::TestScorer::with_penalty(0);
9933         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9934         let route = find_route(
9935                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9936                 nodes[0].logger, &scorer, &random_seed_bytes
9937         ).unwrap();
9938
9939         let test_preimage = PaymentPreimage([42; 32]);
9940         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9941         check_added_monitors!(nodes[0], 1);
9942         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9943         assert_eq!(events.len(), 1);
9944         let event = events.pop().unwrap();
9945         let path = vec![&nodes[1]];
9946         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9947         claim_payment(&nodes[0], &path, test_preimage);
9948 }
9949
9950 #[test]
9951 fn test_double_partial_claim() {
9952         // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9953         // time out, the sender resends only some of the MPP parts, then the user processes the
9954         // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9955         // amount.
9956         let chanmon_cfgs = create_chanmon_cfgs(4);
9957         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9958         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9959         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9960
9961         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9962         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9963         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9964         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9965
9966         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9967         assert_eq!(route.paths.len(), 2);
9968         route.paths.sort_by(|path_a, _| {
9969                 // Sort the path so that the path through nodes[1] comes first
9970                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9971                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9972         });
9973
9974         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9975         // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
9976         // amount of time to respond to.
9977
9978         // Connect some blocks to time out the payment
9979         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9980         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9981
9982         expect_pending_htlcs_forwardable!(nodes[3]);
9983
9984         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9985
9986         // nodes[1] now retries one of the two paths...
9987         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9988         check_added_monitors!(nodes[0], 2);
9989
9990         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9991         assert_eq!(events.len(), 2);
9992         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
9993
9994         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9995         // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
9996         nodes[3].node.claim_funds(payment_preimage);
9997         check_added_monitors!(nodes[3], 0);
9998         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9999 }
10000
10001 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10002         // Test what happens if a node receives an MPP payment, claims it, but crashes before
10003         // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10004         // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10005         // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10006         // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10007         // not have the preimage tied to the still-pending HTLC.
10008         //
10009         // To get to the correct state, on startup we should propagate the preimage to the
10010         // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10011         // receiving the preimage without a state update.
10012         //
10013         // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10014         // definitely claimed.
10015         let chanmon_cfgs = create_chanmon_cfgs(4);
10016         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10017         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10018
10019         let persister: test_utils::TestPersister;
10020         let new_chain_monitor: test_utils::TestChainMonitor;
10021         let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10022
10023         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10024
10025         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10026         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10027         let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10028         let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10029
10030         // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10031         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10032         assert_eq!(route.paths.len(), 2);
10033         route.paths.sort_by(|path_a, _| {
10034                 // Sort the path so that the path through nodes[1] comes first
10035                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10036                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10037         });
10038
10039         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10040         check_added_monitors!(nodes[0], 2);
10041
10042         // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10043         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10044         assert_eq!(send_events.len(), 2);
10045         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);
10046         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);
10047
10048         // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10049         // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10050         let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10051         if !persist_both_monitors {
10052                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10053                         if outpoint.to_channel_id() == chan_id_not_persisted {
10054                                 assert!(original_monitor.0.is_empty());
10055                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10056                         }
10057                 }
10058         }
10059
10060         let mut original_manager = test_utils::TestVecWriter(Vec::new());
10061         nodes[3].node.write(&mut original_manager).unwrap();
10062
10063         expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10064
10065         nodes[3].node.claim_funds(payment_preimage);
10066         check_added_monitors!(nodes[3], 2);
10067         expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10068
10069         // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10070         // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10071         // with the old ChannelManager.
10072         let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10073         for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10074                 if outpoint.to_channel_id() == chan_id_persisted {
10075                         assert!(updated_monitor.0.is_empty());
10076                         nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10077                 }
10078         }
10079         // If `persist_both_monitors` is set, get the second monitor here as well
10080         if persist_both_monitors {
10081                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10082                         if outpoint.to_channel_id() == chan_id_not_persisted {
10083                                 assert!(original_monitor.0.is_empty());
10084                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10085                         }
10086                 }
10087         }
10088
10089         // Now restart nodes[3].
10090         persister = test_utils::TestPersister::new();
10091         let keys_manager = &chanmon_cfgs[3].keys_manager;
10092         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);
10093         nodes[3].chain_monitor = &new_chain_monitor;
10094         let mut monitors = Vec::new();
10095         for mut monitor_data in [original_monitor, updated_monitor].iter() {
10096                 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10097                 monitors.push(deserialized_monitor);
10098         }
10099
10100         let config = UserConfig::default();
10101         nodes_3_deserialized = {
10102                 let mut channel_monitors = HashMap::new();
10103                 for monitor in monitors.iter_mut() {
10104                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10105                 }
10106                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10107                         default_config: config,
10108                         keys_manager,
10109                         fee_estimator: node_cfgs[3].fee_estimator,
10110                         chain_monitor: nodes[3].chain_monitor,
10111                         tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10112                         logger: nodes[3].logger,
10113                         channel_monitors,
10114                 }).unwrap().1
10115         };
10116         nodes[3].node = &nodes_3_deserialized;
10117
10118         for monitor in monitors {
10119                 // On startup the preimage should have been copied into the non-persisted monitor:
10120                 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10121                 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10122         }
10123         check_added_monitors!(nodes[3], 2);
10124
10125         nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10126         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10127
10128         // During deserialization, we should have closed one channel and broadcast its latest
10129         // commitment transaction. We should also still have the original PaymentReceived event we
10130         // never finished processing.
10131         let events = nodes[3].node.get_and_clear_pending_events();
10132         assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10133         if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10134         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10135         if persist_both_monitors {
10136                 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10137         }
10138
10139         // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10140         // ChannelManager prior to handling the original one.
10141         if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10142                 events[if persist_both_monitors { 3 } else { 2 }]
10143         {
10144                 assert_eq!(payment_hash, our_payment_hash);
10145         } else { panic!(); }
10146
10147         assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10148         if !persist_both_monitors {
10149                 // If one of the two channels is still live, reveal the payment preimage over it.
10150
10151                 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10152                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10153                 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10154                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10155
10156                 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10157                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10158                 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10159
10160                 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10161
10162                 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10163                 // claim should fly.
10164                 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10165                 check_added_monitors!(nodes[3], 1);
10166                 assert_eq!(ds_msgs.len(), 2);
10167                 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10168
10169                 let cs_updates = match ds_msgs[0] {
10170                         MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10171                                 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10172                                 check_added_monitors!(nodes[2], 1);
10173                                 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10174                                 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10175                                 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10176                                 cs_updates
10177                         }
10178                         _ => panic!(),
10179                 };
10180
10181                 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10182                 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10183                 expect_payment_sent!(nodes[0], payment_preimage);
10184         }
10185 }
10186
10187 #[test]
10188 fn test_partial_claim_before_restart() {
10189         do_test_partial_claim_before_restart(false);
10190         do_test_partial_claim_before_restart(true);
10191 }
10192
10193 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10194 #[derive(Clone, Copy, PartialEq)]
10195 enum ExposureEvent {
10196         /// Breach occurs at HTLC forwarding (see `send_htlc`)
10197         AtHTLCForward,
10198         /// Breach occurs at HTLC reception (see `update_add_htlc`)
10199         AtHTLCReception,
10200         /// Breach occurs at outbound update_fee (see `send_update_fee`)
10201         AtUpdateFeeOutbound,
10202 }
10203
10204 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10205         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10206         // policy.
10207         //
10208         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10209         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10210         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10211         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10212         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10213         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10214         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10215         // might be available again for HTLC processing once the dust bandwidth has cleared up.
10216
10217         let chanmon_cfgs = create_chanmon_cfgs(2);
10218         let mut config = test_default_channel_config();
10219         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10220         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10221         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10222         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10223
10224         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10225         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10226         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10227         open_channel.max_accepted_htlcs = 60;
10228         if on_holder_tx {
10229                 open_channel.dust_limit_satoshis = 546;
10230         }
10231         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10232         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10233         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10234
10235         let opt_anchors = false;
10236
10237         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10238
10239         if on_holder_tx {
10240                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10241                         chan.holder_dust_limit_satoshis = 546;
10242                 }
10243         }
10244
10245         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10246         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()));
10247         check_added_monitors!(nodes[1], 1);
10248
10249         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()));
10250         check_added_monitors!(nodes[0], 1);
10251
10252         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10253         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10254         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10255
10256         let dust_buffer_feerate = {
10257                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10258                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10259                 chan.get_dust_buffer_feerate(None) as u64
10260         };
10261         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;
10262         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10263
10264         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;
10265         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10266
10267         let dust_htlc_on_counterparty_tx: u64 = 25;
10268         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10269
10270         if on_holder_tx {
10271                 if dust_outbound_balance {
10272                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10273                         // Outbound dust balance: 4372 sats
10274                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10275                         for i in 0..dust_outbound_htlc_on_holder_tx {
10276                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10277                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10278                         }
10279                 } else {
10280                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10281                         // Inbound dust balance: 4372 sats
10282                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10283                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10284                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10285                         }
10286                 }
10287         } else {
10288                 if dust_outbound_balance {
10289                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10290                         // Outbound dust balance: 5000 sats
10291                         for i in 0..dust_htlc_on_counterparty_tx {
10292                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10293                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10294                         }
10295                 } else {
10296                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10297                         // Inbound dust balance: 5000 sats
10298                         for _ in 0..dust_htlc_on_counterparty_tx {
10299                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10300                         }
10301                 }
10302         }
10303
10304         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10305         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10306                 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 });
10307                 let mut config = UserConfig::default();
10308                 // With default dust exposure: 5000 sats
10309                 if on_holder_tx {
10310                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10311                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10312                         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)));
10313                 } else {
10314                         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)));
10315                 }
10316         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10317                 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 });
10318                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10319                 check_added_monitors!(nodes[1], 1);
10320                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10321                 assert_eq!(events.len(), 1);
10322                 let payment_event = SendEvent::from_event(events.remove(0));
10323                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10324                 // With default dust exposure: 5000 sats
10325                 if on_holder_tx {
10326                         // Outbound dust balance: 6399 sats
10327                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10328                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10329                         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);
10330                 } else {
10331                         // Outbound dust balance: 5200 sats
10332                         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);
10333                 }
10334         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10335                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10336                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10337                 {
10338                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10339                         *feerate_lock = *feerate_lock * 10;
10340                 }
10341                 nodes[0].node.timer_tick_occurred();
10342                 check_added_monitors!(nodes[0], 1);
10343                 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);
10344         }
10345
10346         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10347         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10348         added_monitors.clear();
10349 }
10350
10351 #[test]
10352 fn test_max_dust_htlc_exposure() {
10353         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10354         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10355         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10356         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10357         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10358         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10359         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10360         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10361         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10362         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10363         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10364         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10365 }
10366
10367 #[test]
10368 fn test_non_final_funding_tx() {
10369         let chanmon_cfgs = create_chanmon_cfgs(2);
10370         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10371         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10372         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10373
10374         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10375         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10376         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
10377         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10378         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
10379
10380         let best_height = nodes[0].node.best_block.read().unwrap().height();
10381
10382         let chan_id = *nodes[0].network_chan_count.borrow();
10383         let events = nodes[0].node.get_and_clear_pending_events();
10384         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: 0x1, witness: Witness::from_vec(vec!(vec!(1))) };
10385         assert_eq!(events.len(), 1);
10386         let mut tx = match events[0] {
10387                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10388                         // Timelock the transaction _beyond_ the best client height + 2.
10389                         Transaction { version: chan_id as i32, lock_time: best_height + 3, input: vec![input], output: vec![TxOut {
10390                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10391                         }]}
10392                 },
10393                 _ => panic!("Unexpected event"),
10394         };
10395         // Transaction should fail as it's evaluated as non-final for propagation.
10396         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10397                 Err(APIError::APIMisuseError { err }) => {
10398                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10399                 },
10400                 _ => panic!()
10401         }
10402
10403         // However, transaction should be accepted if it's in a +2 headroom from best block.
10404         tx.lock_time -= 1;
10405         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10406         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10407 }