Don't fail HTLCs in revoked commitment txn until we spend them
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use chain;
15 use chain::{Confirm, Listen, Watch};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{BaseSign, KeysInterface};
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS };
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
26 use routing::gossip::NetworkGraph;
27 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
28 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
29 use ln::msgs;
30 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, OptionalField, ErrorAction};
31 use util::enforcing_trait_impls::EnforcingSigner;
32 use util::{byte_utils, test_utils};
33 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
34 use util::errors::APIError;
35 use util::ser::{Writeable, ReadableArgs};
36 use util::config::UserConfig;
37
38 use bitcoin::hash_types::BlockHash;
39 use bitcoin::blockdata::block::{Block, BlockHeader};
40 use bitcoin::blockdata::script::Builder;
41 use bitcoin::blockdata::opcodes;
42 use bitcoin::blockdata::constants::genesis_block;
43 use bitcoin::network::constants::Network;
44
45 use bitcoin::secp256k1::Secp256k1;
46 use bitcoin::secp256k1::{PublicKey,SecretKey};
47
48 use regex;
49
50 use io;
51 use prelude::*;
52 use alloc::collections::BTreeSet;
53 use core::default::Default;
54 use sync::{Arc, Mutex};
55
56 use ln::functional_test_utils::*;
57 use ln::chan_utils::CommitmentTransaction;
58
59 #[test]
60 fn test_insane_channel_opens() {
61         // Stand up a network of 2 nodes
62         use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
63         let mut cfg = UserConfig::default();
64         cfg.peer_channel_config_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
65         let chanmon_cfgs = create_chanmon_cfgs(2);
66         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
67         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
68         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
69
70         // Instantiate channel parameters where we push the maximum msats given our
71         // funding satoshis
72         let channel_value_sat = 31337; // same as funding satoshis
73         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
74         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
75
76         // Have node0 initiate a channel to node1 with aforementioned parameters
77         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
78
79         // Extract the channel open message from node0 to node1
80         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
81
82         // Test helper that asserts we get the correct error string given a mutator
83         // that supposedly makes the channel open message insane
84         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
85                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
86                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
87                 assert_eq!(msg_events.len(), 1);
88                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
89                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
90                         match action {
91                                 &ErrorAction::SendErrorMessage { .. } => {
92                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
93                                 },
94                                 _ => panic!("unexpected event!"),
95                         }
96                 } else { assert!(false); }
97         };
98
99         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
100
101         // Test all mutations that would make the channel open message insane
102         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 });
103         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 });
104
105         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
106
107         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 });
108
109         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
110
111         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 });
112
113         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 });
114
115         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
116
117         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
118 }
119
120 #[test]
121 fn test_funding_exceeds_no_wumbo_limit() {
122         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
123         // them.
124         use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
125         let chanmon_cfgs = create_chanmon_cfgs(2);
126         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
127         node_cfgs[1].features = InitFeatures::known().clear_wumbo();
128         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
129         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
130
131         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
132                 Err(APIError::APIMisuseError { err }) => {
133                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
134                 },
135                 _ => panic!()
136         }
137 }
138
139 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
140         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
141         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
142         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
143         // in normal testing, we test it explicitly here.
144         let chanmon_cfgs = create_chanmon_cfgs(2);
145         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
146         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
147         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
148
149         // Have node0 initiate a channel to node1 with aforementioned parameters
150         let mut push_amt = 100_000_000;
151         let feerate_per_kw = 253;
152         let opt_anchors = false;
153         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
154         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
155
156         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();
157         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
158         if !send_from_initiator {
159                 open_channel_message.channel_reserve_satoshis = 0;
160                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
161         }
162         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
163
164         // Extract the channel accept message from node1 to node0
165         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
166         if send_from_initiator {
167                 accept_channel_message.channel_reserve_satoshis = 0;
168                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
169         }
170         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
171         {
172                 let mut lock;
173                 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
174                 chan.holder_selected_channel_reserve_satoshis = 0;
175                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
176         }
177
178         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
179         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
180         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
181
182         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
183         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
184         if send_from_initiator {
185                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
186                         // Note that for outbound channels we have to consider the commitment tx fee and the
187                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
188                         // well as an additional HTLC.
189                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
190         } else {
191                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
192         }
193 }
194
195 #[test]
196 fn test_counterparty_no_reserve() {
197         do_test_counterparty_no_reserve(true);
198         do_test_counterparty_no_reserve(false);
199 }
200
201 #[test]
202 fn test_async_inbound_update_fee() {
203         let chanmon_cfgs = create_chanmon_cfgs(2);
204         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
205         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
206         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
207         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
208
209         // balancing
210         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
211
212         // A                                        B
213         // update_fee                            ->
214         // send (1) commitment_signed            -.
215         //                                       <- update_add_htlc/commitment_signed
216         // send (2) RAA (awaiting remote revoke) -.
217         // (1) commitment_signed is delivered    ->
218         //                                       .- send (3) RAA (awaiting remote revoke)
219         // (2) RAA is delivered                  ->
220         //                                       .- send (4) commitment_signed
221         //                                       <- (3) RAA is delivered
222         // send (5) commitment_signed            -.
223         //                                       <- (4) commitment_signed is delivered
224         // send (6) RAA                          -.
225         // (5) commitment_signed is delivered    ->
226         //                                       <- RAA
227         // (6) RAA is delivered                  ->
228
229         // First nodes[0] generates an update_fee
230         {
231                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
232                 *feerate_lock += 20;
233         }
234         nodes[0].node.timer_tick_occurred();
235         check_added_monitors!(nodes[0], 1);
236
237         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
238         assert_eq!(events_0.len(), 1);
239         let (update_msg, commitment_signed) = match events_0[0] { // (1)
240                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
241                         (update_fee.as_ref(), commitment_signed)
242                 },
243                 _ => panic!("Unexpected event"),
244         };
245
246         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
247
248         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
249         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
250         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
251         check_added_monitors!(nodes[1], 1);
252
253         let payment_event = {
254                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
255                 assert_eq!(events_1.len(), 1);
256                 SendEvent::from_event(events_1.remove(0))
257         };
258         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
259         assert_eq!(payment_event.msgs.len(), 1);
260
261         // ...now when the messages get delivered everyone should be happy
262         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
263         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
264         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
265         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
266         check_added_monitors!(nodes[0], 1);
267
268         // deliver(1), generate (3):
269         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
270         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
271         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
272         check_added_monitors!(nodes[1], 1);
273
274         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
275         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
276         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
277         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
278         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
279         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
280         assert!(bs_update.update_fee.is_none()); // (4)
281         check_added_monitors!(nodes[1], 1);
282
283         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
284         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
285         assert!(as_update.update_add_htlcs.is_empty()); // (5)
286         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
287         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
288         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
289         assert!(as_update.update_fee.is_none()); // (5)
290         check_added_monitors!(nodes[0], 1);
291
292         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
293         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
294         // only (6) so get_event_msg's assert(len == 1) passes
295         check_added_monitors!(nodes[0], 1);
296
297         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
298         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
299         check_added_monitors!(nodes[1], 1);
300
301         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
302         check_added_monitors!(nodes[0], 1);
303
304         let events_2 = nodes[0].node.get_and_clear_pending_events();
305         assert_eq!(events_2.len(), 1);
306         match events_2[0] {
307                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
308                 _ => panic!("Unexpected event"),
309         }
310
311         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
312         check_added_monitors!(nodes[1], 1);
313 }
314
315 #[test]
316 fn test_update_fee_unordered_raa() {
317         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
318         // crash in an earlier version of the update_fee patch)
319         let chanmon_cfgs = create_chanmon_cfgs(2);
320         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
321         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
322         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
323         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
324
325         // balancing
326         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
327
328         // First nodes[0] generates an update_fee
329         {
330                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
331                 *feerate_lock += 20;
332         }
333         nodes[0].node.timer_tick_occurred();
334         check_added_monitors!(nodes[0], 1);
335
336         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
337         assert_eq!(events_0.len(), 1);
338         let update_msg = match events_0[0] { // (1)
339                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
340                         update_fee.as_ref()
341                 },
342                 _ => panic!("Unexpected event"),
343         };
344
345         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
346
347         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
348         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
349         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
350         check_added_monitors!(nodes[1], 1);
351
352         let payment_event = {
353                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
354                 assert_eq!(events_1.len(), 1);
355                 SendEvent::from_event(events_1.remove(0))
356         };
357         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
358         assert_eq!(payment_event.msgs.len(), 1);
359
360         // ...now when the messages get delivered everyone should be happy
361         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
362         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
363         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
364         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
365         check_added_monitors!(nodes[0], 1);
366
367         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
368         check_added_monitors!(nodes[1], 1);
369
370         // We can't continue, sadly, because our (1) now has a bogus signature
371 }
372
373 #[test]
374 fn test_multi_flight_update_fee() {
375         let chanmon_cfgs = create_chanmon_cfgs(2);
376         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
377         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
378         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
379         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
380
381         // A                                        B
382         // update_fee/commitment_signed          ->
383         //                                       .- send (1) RAA and (2) commitment_signed
384         // update_fee (never committed)          ->
385         // (3) update_fee                        ->
386         // We have to manually generate the above update_fee, it is allowed by the protocol but we
387         // don't track which updates correspond to which revoke_and_ack responses so we're in
388         // AwaitingRAA mode and will not generate the update_fee yet.
389         //                                       <- (1) RAA delivered
390         // (3) is generated and send (4) CS      -.
391         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
392         // know the per_commitment_point to use for it.
393         //                                       <- (2) commitment_signed delivered
394         // revoke_and_ack                        ->
395         //                                          B should send no response here
396         // (4) commitment_signed delivered       ->
397         //                                       <- RAA/commitment_signed delivered
398         // revoke_and_ack                        ->
399
400         // First nodes[0] generates an update_fee
401         let initial_feerate;
402         {
403                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
404                 initial_feerate = *feerate_lock;
405                 *feerate_lock = initial_feerate + 20;
406         }
407         nodes[0].node.timer_tick_occurred();
408         check_added_monitors!(nodes[0], 1);
409
410         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
411         assert_eq!(events_0.len(), 1);
412         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
413                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
414                         (update_fee.as_ref().unwrap(), commitment_signed)
415                 },
416                 _ => panic!("Unexpected event"),
417         };
418
419         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
420         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
421         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
422         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
423         check_added_monitors!(nodes[1], 1);
424
425         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
426         // transaction:
427         {
428                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
429                 *feerate_lock = initial_feerate + 40;
430         }
431         nodes[0].node.timer_tick_occurred();
432         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
433         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
434
435         // Create the (3) update_fee message that nodes[0] will generate before it does...
436         let mut update_msg_2 = msgs::UpdateFee {
437                 channel_id: update_msg_1.channel_id.clone(),
438                 feerate_per_kw: (initial_feerate + 30) as u32,
439         };
440
441         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
442
443         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
444         // Deliver (3)
445         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
446
447         // Deliver (1), generating (3) and (4)
448         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
449         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
450         check_added_monitors!(nodes[0], 1);
451         assert!(as_second_update.update_add_htlcs.is_empty());
452         assert!(as_second_update.update_fulfill_htlcs.is_empty());
453         assert!(as_second_update.update_fail_htlcs.is_empty());
454         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
455         // Check that the update_fee newly generated matches what we delivered:
456         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
457         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
458
459         // Deliver (2) commitment_signed
460         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
461         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
462         check_added_monitors!(nodes[0], 1);
463         // No commitment_signed so get_event_msg's assert(len == 1) passes
464
465         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
466         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
467         check_added_monitors!(nodes[1], 1);
468
469         // Delever (4)
470         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
471         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
472         check_added_monitors!(nodes[1], 1);
473
474         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
475         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
476         check_added_monitors!(nodes[0], 1);
477
478         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
479         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
480         // No commitment_signed so get_event_msg's assert(len == 1) passes
481         check_added_monitors!(nodes[0], 1);
482
483         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
484         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
485         check_added_monitors!(nodes[1], 1);
486 }
487
488 fn do_test_sanity_on_in_flight_opens(steps: u8) {
489         // Previously, we had issues deserializing channels when we hadn't connected the first block
490         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
491         // serialization round-trips and simply do steps towards opening a channel and then drop the
492         // Node objects.
493
494         let chanmon_cfgs = create_chanmon_cfgs(2);
495         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
496         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
497         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
498
499         if steps & 0b1000_0000 != 0{
500                 let block = Block {
501                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
502                         txdata: vec![],
503                 };
504                 connect_block(&nodes[0], &block);
505                 connect_block(&nodes[1], &block);
506         }
507
508         if steps & 0x0f == 0 { return; }
509         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
510         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
511
512         if steps & 0x0f == 1 { return; }
513         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
514         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
515
516         if steps & 0x0f == 2 { return; }
517         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
518
519         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
520
521         if steps & 0x0f == 3 { return; }
522         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
523         check_added_monitors!(nodes[0], 0);
524         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
525
526         if steps & 0x0f == 4 { return; }
527         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
528         {
529                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
530                 assert_eq!(added_monitors.len(), 1);
531                 assert_eq!(added_monitors[0].0, funding_output);
532                 added_monitors.clear();
533         }
534         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
535
536         if steps & 0x0f == 5 { return; }
537         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
538         {
539                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
540                 assert_eq!(added_monitors.len(), 1);
541                 assert_eq!(added_monitors[0].0, funding_output);
542                 added_monitors.clear();
543         }
544
545         let events_4 = nodes[0].node.get_and_clear_pending_events();
546         assert_eq!(events_4.len(), 0);
547
548         if steps & 0x0f == 6 { return; }
549         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
550
551         if steps & 0x0f == 7 { return; }
552         confirm_transaction_at(&nodes[0], &tx, 2);
553         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
554         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
555 }
556
557 #[test]
558 fn test_sanity_on_in_flight_opens() {
559         do_test_sanity_on_in_flight_opens(0);
560         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
561         do_test_sanity_on_in_flight_opens(1);
562         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
563         do_test_sanity_on_in_flight_opens(2);
564         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
565         do_test_sanity_on_in_flight_opens(3);
566         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
567         do_test_sanity_on_in_flight_opens(4);
568         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
569         do_test_sanity_on_in_flight_opens(5);
570         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
571         do_test_sanity_on_in_flight_opens(6);
572         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
573         do_test_sanity_on_in_flight_opens(7);
574         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
575         do_test_sanity_on_in_flight_opens(8);
576         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
577 }
578
579 #[test]
580 fn test_update_fee_vanilla() {
581         let chanmon_cfgs = create_chanmon_cfgs(2);
582         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
583         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
584         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
585         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
586
587         {
588                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
589                 *feerate_lock += 25;
590         }
591         nodes[0].node.timer_tick_occurred();
592         check_added_monitors!(nodes[0], 1);
593
594         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
595         assert_eq!(events_0.len(), 1);
596         let (update_msg, commitment_signed) = match events_0[0] {
597                         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 } } => {
598                         (update_fee.as_ref(), commitment_signed)
599                 },
600                 _ => panic!("Unexpected event"),
601         };
602         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
603
604         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
605         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
606         check_added_monitors!(nodes[1], 1);
607
608         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
609         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
610         check_added_monitors!(nodes[0], 1);
611
612         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
613         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
614         // No commitment_signed so get_event_msg's assert(len == 1) passes
615         check_added_monitors!(nodes[0], 1);
616
617         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
618         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
619         check_added_monitors!(nodes[1], 1);
620 }
621
622 #[test]
623 fn test_update_fee_that_funder_cannot_afford() {
624         let chanmon_cfgs = create_chanmon_cfgs(2);
625         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
626         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
627         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
628         let channel_value = 5000;
629         let push_sats = 700;
630         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
631         let channel_id = chan.2;
632         let secp_ctx = Secp256k1::new();
633         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
634
635         let opt_anchors = false;
636
637         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
638         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
639         // calculate two different feerates here - the expected local limit as well as the expected
640         // remote limit.
641         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;
642         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
643         {
644                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
645                 *feerate_lock = feerate;
646         }
647         nodes[0].node.timer_tick_occurred();
648         check_added_monitors!(nodes[0], 1);
649         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
650
651         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
652
653         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
654
655         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
656         {
657                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
658
659                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
660                 assert_eq!(commitment_tx.output.len(), 2);
661                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
662                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
663                 actual_fee = channel_value - actual_fee;
664                 assert_eq!(total_fee, actual_fee);
665         }
666
667         {
668                 // Increment the feerate by a small constant, accounting for rounding errors
669                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
670                 *feerate_lock += 4;
671         }
672         nodes[0].node.timer_tick_occurred();
673         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
674         check_added_monitors!(nodes[0], 0);
675
676         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
677
678         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
679         // needed to sign the new commitment tx and (2) sign the new commitment tx.
680         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
681                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
682                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
683                 let chan_signer = local_chan.get_signer();
684                 let pubkeys = chan_signer.pubkeys();
685                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
686                  pubkeys.funding_pubkey)
687         };
688         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
689                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
690                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
691                 let chan_signer = remote_chan.get_signer();
692                 let pubkeys = chan_signer.pubkeys();
693                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
694                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
695                  pubkeys.funding_pubkey)
696         };
697
698         // Assemble the set of keys we can use for signatures for our commitment_signed message.
699         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
700                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
701
702         let res = {
703                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
704                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
705                 let local_chan_signer = local_chan.get_signer();
706                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
707                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
708                         INITIAL_COMMITMENT_NUMBER - 1,
709                         push_sats,
710                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
711                         opt_anchors, local_funding, remote_funding,
712                         commit_tx_keys.clone(),
713                         non_buffer_feerate + 4,
714                         &mut htlcs,
715                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
716                 );
717                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
718         };
719
720         let commit_signed_msg = msgs::CommitmentSigned {
721                 channel_id: chan.2,
722                 signature: res.0,
723                 htlc_signatures: res.1
724         };
725
726         let update_fee = msgs::UpdateFee {
727                 channel_id: chan.2,
728                 feerate_per_kw: non_buffer_feerate + 4,
729         };
730
731         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
732
733         //While producing the commitment_signed response after handling a received update_fee request the
734         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
735         //Should produce and error.
736         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
737         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
738         check_added_monitors!(nodes[1], 1);
739         check_closed_broadcast!(nodes[1], true);
740         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
741 }
742
743 #[test]
744 fn test_update_fee_with_fundee_update_add_htlc() {
745         let chanmon_cfgs = create_chanmon_cfgs(2);
746         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
747         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
748         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
749         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
750
751         // balancing
752         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
753
754         {
755                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
756                 *feerate_lock += 20;
757         }
758         nodes[0].node.timer_tick_occurred();
759         check_added_monitors!(nodes[0], 1);
760
761         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
762         assert_eq!(events_0.len(), 1);
763         let (update_msg, commitment_signed) = match events_0[0] {
764                         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 } } => {
765                         (update_fee.as_ref(), commitment_signed)
766                 },
767                 _ => panic!("Unexpected event"),
768         };
769         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
770         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
771         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
772         check_added_monitors!(nodes[1], 1);
773
774         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
775
776         // nothing happens since node[1] is in AwaitingRemoteRevoke
777         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
778         {
779                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
780                 assert_eq!(added_monitors.len(), 0);
781                 added_monitors.clear();
782         }
783         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
784         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
785         // node[1] has nothing to do
786
787         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
788         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
789         check_added_monitors!(nodes[0], 1);
790
791         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
792         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
793         // No commitment_signed so get_event_msg's assert(len == 1) passes
794         check_added_monitors!(nodes[0], 1);
795         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
796         check_added_monitors!(nodes[1], 1);
797         // AwaitingRemoteRevoke ends here
798
799         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
800         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
801         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
802         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
803         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
804         assert_eq!(commitment_update.update_fee.is_none(), true);
805
806         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
807         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
808         check_added_monitors!(nodes[0], 1);
809         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
810
811         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
812         check_added_monitors!(nodes[1], 1);
813         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
814
815         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
816         check_added_monitors!(nodes[1], 1);
817         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
818         // No commitment_signed so get_event_msg's assert(len == 1) passes
819
820         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
821         check_added_monitors!(nodes[0], 1);
822         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
823
824         expect_pending_htlcs_forwardable!(nodes[0]);
825
826         let events = nodes[0].node.get_and_clear_pending_events();
827         assert_eq!(events.len(), 1);
828         match events[0] {
829                 Event::PaymentReceived { .. } => { },
830                 _ => panic!("Unexpected event"),
831         };
832
833         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
834
835         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
836         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
837         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
838         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
839         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
840 }
841
842 #[test]
843 fn test_update_fee() {
844         let chanmon_cfgs = create_chanmon_cfgs(2);
845         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
846         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
847         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
848         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
849         let channel_id = chan.2;
850
851         // A                                        B
852         // (1) update_fee/commitment_signed      ->
853         //                                       <- (2) revoke_and_ack
854         //                                       .- send (3) commitment_signed
855         // (4) update_fee/commitment_signed      ->
856         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
857         //                                       <- (3) commitment_signed delivered
858         // send (6) revoke_and_ack               -.
859         //                                       <- (5) deliver revoke_and_ack
860         // (6) deliver revoke_and_ack            ->
861         //                                       .- send (7) commitment_signed in response to (4)
862         //                                       <- (7) deliver commitment_signed
863         // revoke_and_ack                        ->
864
865         // Create and deliver (1)...
866         let feerate;
867         {
868                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
869                 feerate = *feerate_lock;
870                 *feerate_lock = feerate + 20;
871         }
872         nodes[0].node.timer_tick_occurred();
873         check_added_monitors!(nodes[0], 1);
874
875         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
876         assert_eq!(events_0.len(), 1);
877         let (update_msg, commitment_signed) = match events_0[0] {
878                         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 } } => {
879                         (update_fee.as_ref(), commitment_signed)
880                 },
881                 _ => panic!("Unexpected event"),
882         };
883         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
884
885         // Generate (2) and (3):
886         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
887         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
888         check_added_monitors!(nodes[1], 1);
889
890         // Deliver (2):
891         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
892         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
893         check_added_monitors!(nodes[0], 1);
894
895         // Create and deliver (4)...
896         {
897                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
898                 *feerate_lock = feerate + 30;
899         }
900         nodes[0].node.timer_tick_occurred();
901         check_added_monitors!(nodes[0], 1);
902         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
903         assert_eq!(events_0.len(), 1);
904         let (update_msg, commitment_signed) = match events_0[0] {
905                         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 } } => {
906                         (update_fee.as_ref(), commitment_signed)
907                 },
908                 _ => panic!("Unexpected event"),
909         };
910
911         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
912         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
913         check_added_monitors!(nodes[1], 1);
914         // ... creating (5)
915         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
916         // No commitment_signed so get_event_msg's assert(len == 1) passes
917
918         // Handle (3), creating (6):
919         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
920         check_added_monitors!(nodes[0], 1);
921         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
922         // No commitment_signed so get_event_msg's assert(len == 1) passes
923
924         // Deliver (5):
925         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
926         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
927         check_added_monitors!(nodes[0], 1);
928
929         // Deliver (6), creating (7):
930         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
931         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
932         assert!(commitment_update.update_add_htlcs.is_empty());
933         assert!(commitment_update.update_fulfill_htlcs.is_empty());
934         assert!(commitment_update.update_fail_htlcs.is_empty());
935         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
936         assert!(commitment_update.update_fee.is_none());
937         check_added_monitors!(nodes[1], 1);
938
939         // Deliver (7)
940         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
941         check_added_monitors!(nodes[0], 1);
942         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
943         // No commitment_signed so get_event_msg's assert(len == 1) passes
944
945         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
946         check_added_monitors!(nodes[1], 1);
947         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
948
949         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
950         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
951         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
952         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
953         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
954 }
955
956 #[test]
957 fn fake_network_test() {
958         // Simple test which builds a network of ChannelManagers, connects them to each other, and
959         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
960         let chanmon_cfgs = create_chanmon_cfgs(4);
961         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
962         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
963         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
964
965         // Create some initial channels
966         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
967         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
968         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
969
970         // Rebalance the network a bit by relaying one payment through all the channels...
971         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
972         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
973         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
974         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
975
976         // Send some more payments
977         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
978         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
979         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
980
981         // Test failure packets
982         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
983         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
984
985         // Add a new channel that skips 3
986         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
987
988         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
989         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
990         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
991         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
992         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
993         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
994         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
995
996         // Do some rebalance loop payments, simultaneously
997         let mut hops = Vec::with_capacity(3);
998         hops.push(RouteHop {
999                 pubkey: nodes[2].node.get_our_node_id(),
1000                 node_features: NodeFeatures::empty(),
1001                 short_channel_id: chan_2.0.contents.short_channel_id,
1002                 channel_features: ChannelFeatures::empty(),
1003                 fee_msat: 0,
1004                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1005         });
1006         hops.push(RouteHop {
1007                 pubkey: nodes[3].node.get_our_node_id(),
1008                 node_features: NodeFeatures::empty(),
1009                 short_channel_id: chan_3.0.contents.short_channel_id,
1010                 channel_features: ChannelFeatures::empty(),
1011                 fee_msat: 0,
1012                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1013         });
1014         hops.push(RouteHop {
1015                 pubkey: nodes[1].node.get_our_node_id(),
1016                 node_features: NodeFeatures::known(),
1017                 short_channel_id: chan_4.0.contents.short_channel_id,
1018                 channel_features: ChannelFeatures::known(),
1019                 fee_msat: 1000000,
1020                 cltv_expiry_delta: TEST_FINAL_CLTV,
1021         });
1022         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;
1023         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;
1024         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;
1025
1026         let mut hops = Vec::with_capacity(3);
1027         hops.push(RouteHop {
1028                 pubkey: nodes[3].node.get_our_node_id(),
1029                 node_features: NodeFeatures::empty(),
1030                 short_channel_id: chan_4.0.contents.short_channel_id,
1031                 channel_features: ChannelFeatures::empty(),
1032                 fee_msat: 0,
1033                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1034         });
1035         hops.push(RouteHop {
1036                 pubkey: nodes[2].node.get_our_node_id(),
1037                 node_features: NodeFeatures::empty(),
1038                 short_channel_id: chan_3.0.contents.short_channel_id,
1039                 channel_features: ChannelFeatures::empty(),
1040                 fee_msat: 0,
1041                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1042         });
1043         hops.push(RouteHop {
1044                 pubkey: nodes[1].node.get_our_node_id(),
1045                 node_features: NodeFeatures::known(),
1046                 short_channel_id: chan_2.0.contents.short_channel_id,
1047                 channel_features: ChannelFeatures::known(),
1048                 fee_msat: 1000000,
1049                 cltv_expiry_delta: TEST_FINAL_CLTV,
1050         });
1051         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;
1052         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;
1053         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;
1054
1055         // Claim the rebalances...
1056         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1057         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1058
1059         // Add a duplicate new channel from 2 to 4
1060         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1061
1062         // Send some payments across both channels
1063         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1064         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1065         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1066
1067
1068         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1069         let events = nodes[0].node.get_and_clear_pending_msg_events();
1070         assert_eq!(events.len(), 0);
1071         nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1072
1073         //TODO: Test that routes work again here as we've been notified that the channel is full
1074
1075         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1076         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1077         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1078
1079         // Close down the channels...
1080         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1081         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1082         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1083         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1084         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1085         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1086         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1087         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1088         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1089         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1090         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1091         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1092         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1093         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1094         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1095 }
1096
1097 #[test]
1098 fn holding_cell_htlc_counting() {
1099         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1100         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1101         // commitment dance rounds.
1102         let chanmon_cfgs = create_chanmon_cfgs(3);
1103         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1104         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1105         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1106         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1107         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1108
1109         let mut payments = Vec::new();
1110         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1111                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1112                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1113                 payments.push((payment_preimage, payment_hash));
1114         }
1115         check_added_monitors!(nodes[1], 1);
1116
1117         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1118         assert_eq!(events.len(), 1);
1119         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1120         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1121
1122         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1123         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1124         // another HTLC.
1125         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1126         {
1127                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1128                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1129                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1130                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1131         }
1132
1133         // This should also be true if we try to forward a payment.
1134         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1135         {
1136                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1137                 check_added_monitors!(nodes[0], 1);
1138         }
1139
1140         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1141         assert_eq!(events.len(), 1);
1142         let payment_event = SendEvent::from_event(events.pop().unwrap());
1143         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1144
1145         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1146         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1147         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1148         // fails), the second will process the resulting failure and fail the HTLC backward.
1149         expect_pending_htlcs_forwardable!(nodes[1]);
1150         expect_pending_htlcs_forwardable!(nodes[1]);
1151         check_added_monitors!(nodes[1], 1);
1152
1153         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1154         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1155         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1156
1157         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1158
1159         // Now forward all the pending HTLCs and claim them back
1160         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1161         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1162         check_added_monitors!(nodes[2], 1);
1163
1164         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1165         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1166         check_added_monitors!(nodes[1], 1);
1167         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1168
1169         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1170         check_added_monitors!(nodes[1], 1);
1171         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1172
1173         for ref update in as_updates.update_add_htlcs.iter() {
1174                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1175         }
1176         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1177         check_added_monitors!(nodes[2], 1);
1178         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1179         check_added_monitors!(nodes[2], 1);
1180         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1181
1182         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1183         check_added_monitors!(nodes[1], 1);
1184         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1185         check_added_monitors!(nodes[1], 1);
1186         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1187
1188         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1189         check_added_monitors!(nodes[2], 1);
1190
1191         expect_pending_htlcs_forwardable!(nodes[2]);
1192
1193         let events = nodes[2].node.get_and_clear_pending_events();
1194         assert_eq!(events.len(), payments.len());
1195         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1196                 match event {
1197                         &Event::PaymentReceived { ref payment_hash, .. } => {
1198                                 assert_eq!(*payment_hash, *hash);
1199                         },
1200                         _ => panic!("Unexpected event"),
1201                 };
1202         }
1203
1204         for (preimage, _) in payments.drain(..) {
1205                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1206         }
1207
1208         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1209 }
1210
1211 #[test]
1212 fn duplicate_htlc_test() {
1213         // Test that we accept duplicate payment_hash HTLCs across the network and that
1214         // claiming/failing them are all separate and don't affect each other
1215         let chanmon_cfgs = create_chanmon_cfgs(6);
1216         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1217         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1218         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1219
1220         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1221         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1222         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1223         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1224         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1225         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1226
1227         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1228
1229         *nodes[0].network_payment_count.borrow_mut() -= 1;
1230         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1231
1232         *nodes[0].network_payment_count.borrow_mut() -= 1;
1233         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1234
1235         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1236         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1237         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1238 }
1239
1240 #[test]
1241 fn test_duplicate_htlc_different_direction_onchain() {
1242         // Test that ChannelMonitor doesn't generate 2 preimage txn
1243         // when we have 2 HTLCs with same preimage that go across a node
1244         // in opposite directions, even with the same payment secret.
1245         let chanmon_cfgs = create_chanmon_cfgs(2);
1246         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1247         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1248         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1249
1250         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1251
1252         // balancing
1253         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1254
1255         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1256
1257         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1258         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1259         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1260
1261         // Provide preimage to node 0 by claiming payment
1262         nodes[0].node.claim_funds(payment_preimage);
1263         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1264         check_added_monitors!(nodes[0], 1);
1265
1266         // Broadcast node 1 commitment txn
1267         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1268
1269         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1270         let mut has_both_htlcs = 0; // check htlcs match ones committed
1271         for outp in remote_txn[0].output.iter() {
1272                 if outp.value == 800_000 / 1000 {
1273                         has_both_htlcs += 1;
1274                 } else if outp.value == 900_000 / 1000 {
1275                         has_both_htlcs += 1;
1276                 }
1277         }
1278         assert_eq!(has_both_htlcs, 2);
1279
1280         mine_transaction(&nodes[0], &remote_txn[0]);
1281         check_added_monitors!(nodes[0], 1);
1282         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1283         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1284
1285         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1286         assert_eq!(claim_txn.len(), 8);
1287
1288         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1289
1290         check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1291         check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1292
1293         let bump_tx = if claim_txn[1] == claim_txn[4] {
1294                 assert_eq!(claim_txn[1], claim_txn[4]);
1295                 assert_eq!(claim_txn[2], claim_txn[5]);
1296
1297                 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1298
1299                 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1300                 &claim_txn[3]
1301         } else {
1302                 assert_eq!(claim_txn[1], claim_txn[3]);
1303                 assert_eq!(claim_txn[2], claim_txn[4]);
1304
1305                 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1306
1307                 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1308
1309                 &claim_txn[7]
1310         };
1311
1312         assert_eq!(claim_txn[0].input.len(), 1);
1313         assert_eq!(bump_tx.input.len(), 1);
1314         assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1315
1316         assert_eq!(claim_txn[0].input.len(), 1);
1317         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1318         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1319
1320         assert_eq!(claim_txn[6].input.len(), 1);
1321         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1322         check_spends!(claim_txn[6], remote_txn[0]);
1323         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1324
1325         let events = nodes[0].node.get_and_clear_pending_msg_events();
1326         assert_eq!(events.len(), 3);
1327         for e in events {
1328                 match e {
1329                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1330                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1331                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1332                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1333                         },
1334                         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, .. } } => {
1335                                 assert!(update_add_htlcs.is_empty());
1336                                 assert!(update_fail_htlcs.is_empty());
1337                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1338                                 assert!(update_fail_malformed_htlcs.is_empty());
1339                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1340                         },
1341                         _ => panic!("Unexpected event"),
1342                 }
1343         }
1344 }
1345
1346 #[test]
1347 fn test_basic_channel_reserve() {
1348         let chanmon_cfgs = create_chanmon_cfgs(2);
1349         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1350         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1351         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1352         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1353
1354         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1355         let channel_reserve = chan_stat.channel_reserve_msat;
1356
1357         // The 2* and +1 are for the fee spike reserve.
1358         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1359         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1360         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1361         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1362         match err {
1363                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1364                         match &fails[0] {
1365                                 &APIError::ChannelUnavailable{ref err} =>
1366                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1367                                 _ => panic!("Unexpected error variant"),
1368                         }
1369                 },
1370                 _ => panic!("Unexpected error variant"),
1371         }
1372         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1373         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);
1374
1375         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1376 }
1377
1378 #[test]
1379 fn test_fee_spike_violation_fails_htlc() {
1380         let chanmon_cfgs = create_chanmon_cfgs(2);
1381         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1382         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1383         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1384         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1385
1386         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1387         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1388         let secp_ctx = Secp256k1::new();
1389         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1390
1391         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1392
1393         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1394         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1395         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1396         let msg = msgs::UpdateAddHTLC {
1397                 channel_id: chan.2,
1398                 htlc_id: 0,
1399                 amount_msat: htlc_msat,
1400                 payment_hash: payment_hash,
1401                 cltv_expiry: htlc_cltv,
1402                 onion_routing_packet: onion_packet,
1403         };
1404
1405         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1406
1407         // Now manually create the commitment_signed message corresponding to the update_add
1408         // nodes[0] just sent. In the code for construction of this message, "local" refers
1409         // to the sender of the message, and "remote" refers to the receiver.
1410
1411         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1412
1413         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1414
1415         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1416         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1417         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1418                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1419                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1420                 let chan_signer = local_chan.get_signer();
1421                 // Make the signer believe we validated another commitment, so we can release the secret
1422                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1423
1424                 let pubkeys = chan_signer.pubkeys();
1425                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1426                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1427                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1428                  chan_signer.pubkeys().funding_pubkey)
1429         };
1430         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1431                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1432                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1433                 let chan_signer = remote_chan.get_signer();
1434                 let pubkeys = chan_signer.pubkeys();
1435                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1436                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1437                  chan_signer.pubkeys().funding_pubkey)
1438         };
1439
1440         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1441         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1442                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1443
1444         // Build the remote commitment transaction so we can sign it, and then later use the
1445         // signature for the commitment_signed message.
1446         let local_chan_balance = 1313;
1447
1448         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1449                 offered: false,
1450                 amount_msat: 3460001,
1451                 cltv_expiry: htlc_cltv,
1452                 payment_hash,
1453                 transaction_output_index: Some(1),
1454         };
1455
1456         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1457
1458         let res = {
1459                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1460                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1461                 let local_chan_signer = local_chan.get_signer();
1462                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1463                         commitment_number,
1464                         95000,
1465                         local_chan_balance,
1466                         local_chan.opt_anchors(), local_funding, remote_funding,
1467                         commit_tx_keys.clone(),
1468                         feerate_per_kw,
1469                         &mut vec![(accepted_htlc_info, ())],
1470                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1471                 );
1472                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1473         };
1474
1475         let commit_signed_msg = msgs::CommitmentSigned {
1476                 channel_id: chan.2,
1477                 signature: res.0,
1478                 htlc_signatures: res.1
1479         };
1480
1481         // Send the commitment_signed message to the nodes[1].
1482         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1483         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1484
1485         // Send the RAA to nodes[1].
1486         let raa_msg = msgs::RevokeAndACK {
1487                 channel_id: chan.2,
1488                 per_commitment_secret: local_secret,
1489                 next_per_commitment_point: next_local_point
1490         };
1491         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1492
1493         let events = nodes[1].node.get_and_clear_pending_msg_events();
1494         assert_eq!(events.len(), 1);
1495         // Make sure the HTLC failed in the way we expect.
1496         match events[0] {
1497                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1498                         assert_eq!(update_fail_htlcs.len(), 1);
1499                         update_fail_htlcs[0].clone()
1500                 },
1501                 _ => panic!("Unexpected event"),
1502         };
1503         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1504                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1505
1506         check_added_monitors!(nodes[1], 2);
1507 }
1508
1509 #[test]
1510 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1511         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1512         // Set the fee rate for the channel very high, to the point where the fundee
1513         // sending any above-dust amount would result in a channel reserve violation.
1514         // In this test we check that we would be prevented from sending an HTLC in
1515         // this situation.
1516         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1517         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1518         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1519         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1520
1521         let opt_anchors = false;
1522
1523         let mut push_amt = 100_000_000;
1524         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1525         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1526
1527         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1528
1529         // Sending exactly enough to hit the reserve amount should be accepted
1530         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1531                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1532         }
1533
1534         // However one more HTLC should be significantly over the reserve amount and fail.
1535         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1536         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1537                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1538         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1539         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);
1540 }
1541
1542 #[test]
1543 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1544         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1545         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1546         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1547         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1548         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1549
1550         let opt_anchors = false;
1551
1552         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1553         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1554         // transaction fee with 0 HTLCs (183 sats)).
1555         let mut push_amt = 100_000_000;
1556         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1557         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1558         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1559
1560         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1561         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1562                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1563         }
1564
1565         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1566         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1567         let secp_ctx = Secp256k1::new();
1568         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1569         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1570         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1571         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1572         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1573         let msg = msgs::UpdateAddHTLC {
1574                 channel_id: chan.2,
1575                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1576                 amount_msat: htlc_msat,
1577                 payment_hash: payment_hash,
1578                 cltv_expiry: htlc_cltv,
1579                 onion_routing_packet: onion_packet,
1580         };
1581
1582         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1583         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1584         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);
1585         assert_eq!(nodes[0].node.list_channels().len(), 0);
1586         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1587         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1588         check_added_monitors!(nodes[0], 1);
1589         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() });
1590 }
1591
1592 #[test]
1593 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1594         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1595         // calculating our commitment transaction fee (this was previously broken).
1596         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1597         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1598
1599         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1600         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1601         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1602
1603         let opt_anchors = false;
1604
1605         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1606         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1607         // transaction fee with 0 HTLCs (183 sats)).
1608         let mut push_amt = 100_000_000;
1609         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1610         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1611         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1612
1613         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1614                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1615         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1616         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1617         // commitment transaction fee.
1618         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1619
1620         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1621         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1622                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1623         }
1624
1625         // One more than the dust amt should fail, however.
1626         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1627         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1628                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1629 }
1630
1631 #[test]
1632 fn test_chan_init_feerate_unaffordability() {
1633         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1634         // channel reserve and feerate requirements.
1635         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1636         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1637         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1638         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1639         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1640
1641         let opt_anchors = false;
1642
1643         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1644         // HTLC.
1645         let mut push_amt = 100_000_000;
1646         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1647         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1648                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1649
1650         // During open, we don't have a "counterparty channel reserve" to check against, so that
1651         // requirement only comes into play on the open_channel handling side.
1652         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1653         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1654         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1655         open_channel_msg.push_msat += 1;
1656         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1657
1658         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1659         assert_eq!(msg_events.len(), 1);
1660         match msg_events[0] {
1661                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1662                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1663                 },
1664                 _ => panic!("Unexpected event"),
1665         }
1666 }
1667
1668 #[test]
1669 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1670         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1671         // calculating our counterparty's commitment transaction fee (this was previously broken).
1672         let chanmon_cfgs = create_chanmon_cfgs(2);
1673         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1674         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1675         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1676         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1677
1678         let payment_amt = 46000; // Dust amount
1679         // In the previous code, these first four payments would succeed.
1680         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1681         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1682         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1683         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1684
1685         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1686         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1688         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1690         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1691
1692         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1693         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1694         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1695         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1696 }
1697
1698 #[test]
1699 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1700         let chanmon_cfgs = create_chanmon_cfgs(3);
1701         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1702         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1703         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1704         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1705         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1706
1707         let feemsat = 239;
1708         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1709         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1710         let feerate = get_feerate!(nodes[0], chan.2);
1711         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1712
1713         // Add a 2* and +1 for the fee spike reserve.
1714         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1715         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;
1716         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1717
1718         // Add a pending HTLC.
1719         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1720         let payment_event_1 = {
1721                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1722                 check_added_monitors!(nodes[0], 1);
1723
1724                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1725                 assert_eq!(events.len(), 1);
1726                 SendEvent::from_event(events.remove(0))
1727         };
1728         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1729
1730         // Attempt to trigger a channel reserve violation --> payment failure.
1731         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1732         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;
1733         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1734         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1735
1736         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1737         let secp_ctx = Secp256k1::new();
1738         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1739         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1740         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1741         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1742         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1743         let msg = msgs::UpdateAddHTLC {
1744                 channel_id: chan.2,
1745                 htlc_id: 1,
1746                 amount_msat: htlc_msat + 1,
1747                 payment_hash: our_payment_hash_1,
1748                 cltv_expiry: htlc_cltv,
1749                 onion_routing_packet: onion_packet,
1750         };
1751
1752         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1753         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1754         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1755         assert_eq!(nodes[1].node.list_channels().len(), 1);
1756         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1757         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1758         check_added_monitors!(nodes[1], 1);
1759         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1760 }
1761
1762 #[test]
1763 fn test_inbound_outbound_capacity_is_not_zero() {
1764         let chanmon_cfgs = create_chanmon_cfgs(2);
1765         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1766         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1767         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1768         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1769         let channels0 = node_chanmgrs[0].list_channels();
1770         let channels1 = node_chanmgrs[1].list_channels();
1771         assert_eq!(channels0.len(), 1);
1772         assert_eq!(channels1.len(), 1);
1773
1774         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1775         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1776         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1777
1778         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1779         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1780 }
1781
1782 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1783         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1784 }
1785
1786 #[test]
1787 fn test_channel_reserve_holding_cell_htlcs() {
1788         let chanmon_cfgs = create_chanmon_cfgs(3);
1789         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1790         // When this test was written, the default base fee floated based on the HTLC count.
1791         // It is now fixed, so we simply set the fee to the expected value here.
1792         let mut config = test_default_channel_config();
1793         config.channel_options.forwarding_fee_base_msat = 239;
1794         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1795         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1796         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1797         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1798
1799         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1800         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1801
1802         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1803         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1804
1805         macro_rules! expect_forward {
1806                 ($node: expr) => {{
1807                         let mut events = $node.node.get_and_clear_pending_msg_events();
1808                         assert_eq!(events.len(), 1);
1809                         check_added_monitors!($node, 1);
1810                         let payment_event = SendEvent::from_event(events.remove(0));
1811                         payment_event
1812                 }}
1813         }
1814
1815         let feemsat = 239; // set above
1816         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1817         let feerate = get_feerate!(nodes[0], chan_1.2);
1818         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1819
1820         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1821
1822         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1823         {
1824                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1825                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1826                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1827                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1828                         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)));
1829                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1830                 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);
1831         }
1832
1833         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1834         // nodes[0]'s wealth
1835         loop {
1836                 let amt_msat = recv_value_0 + total_fee_msat;
1837                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1838                 // Also, ensure that each payment has enough to be over the dust limit to
1839                 // ensure it'll be included in each commit tx fee calculation.
1840                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1841                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1842                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1843                         break;
1844                 }
1845                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1846
1847                 let (stat01_, stat11_, stat12_, stat22_) = (
1848                         get_channel_value_stat!(nodes[0], chan_1.2),
1849                         get_channel_value_stat!(nodes[1], chan_1.2),
1850                         get_channel_value_stat!(nodes[1], chan_2.2),
1851                         get_channel_value_stat!(nodes[2], chan_2.2),
1852                 );
1853
1854                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1855                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1856                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1857                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1858                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1859         }
1860
1861         // adding pending output.
1862         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1863         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1864         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1865         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1866         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1867         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1868         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1869         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1870         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1871         // policy.
1872         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1873         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1874         let amt_msat_1 = recv_value_1 + total_fee_msat;
1875
1876         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);
1877         let payment_event_1 = {
1878                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1879                 check_added_monitors!(nodes[0], 1);
1880
1881                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1882                 assert_eq!(events.len(), 1);
1883                 SendEvent::from_event(events.remove(0))
1884         };
1885         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1886
1887         // channel reserve test with htlc pending output > 0
1888         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1889         {
1890                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1891                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1892                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1893                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1894         }
1895
1896         // split the rest to test holding cell
1897         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1898         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1899         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1900         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1901         {
1902                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1903                 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);
1904         }
1905
1906         // now see if they go through on both sides
1907         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);
1908         // but this will stuck in the holding cell
1909         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1910         check_added_monitors!(nodes[0], 0);
1911         let events = nodes[0].node.get_and_clear_pending_events();
1912         assert_eq!(events.len(), 0);
1913
1914         // test with outbound holding cell amount > 0
1915         {
1916                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1917                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1918                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1919                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1920                 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);
1921         }
1922
1923         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);
1924         // this will also stuck in the holding cell
1925         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1926         check_added_monitors!(nodes[0], 0);
1927         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1928         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1929
1930         // flush the pending htlc
1931         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1932         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1933         check_added_monitors!(nodes[1], 1);
1934
1935         // the pending htlc should be promoted to committed
1936         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1937         check_added_monitors!(nodes[0], 1);
1938         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1939
1940         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1941         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1942         // No commitment_signed so get_event_msg's assert(len == 1) passes
1943         check_added_monitors!(nodes[0], 1);
1944
1945         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1946         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1947         check_added_monitors!(nodes[1], 1);
1948
1949         expect_pending_htlcs_forwardable!(nodes[1]);
1950
1951         let ref payment_event_11 = expect_forward!(nodes[1]);
1952         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1953         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1954
1955         expect_pending_htlcs_forwardable!(nodes[2]);
1956         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1957
1958         // flush the htlcs in the holding cell
1959         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1960         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1961         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1962         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1963         expect_pending_htlcs_forwardable!(nodes[1]);
1964
1965         let ref payment_event_3 = expect_forward!(nodes[1]);
1966         assert_eq!(payment_event_3.msgs.len(), 2);
1967         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1968         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1969
1970         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1971         expect_pending_htlcs_forwardable!(nodes[2]);
1972
1973         let events = nodes[2].node.get_and_clear_pending_events();
1974         assert_eq!(events.len(), 2);
1975         match events[0] {
1976                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1977                         assert_eq!(our_payment_hash_21, *payment_hash);
1978                         assert_eq!(recv_value_21, amount_msat);
1979                         match &purpose {
1980                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1981                                         assert!(payment_preimage.is_none());
1982                                         assert_eq!(our_payment_secret_21, *payment_secret);
1983                                 },
1984                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1985                         }
1986                 },
1987                 _ => panic!("Unexpected event"),
1988         }
1989         match events[1] {
1990                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1991                         assert_eq!(our_payment_hash_22, *payment_hash);
1992                         assert_eq!(recv_value_22, amount_msat);
1993                         match &purpose {
1994                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1995                                         assert!(payment_preimage.is_none());
1996                                         assert_eq!(our_payment_secret_22, *payment_secret);
1997                                 },
1998                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1999                         }
2000                 },
2001                 _ => panic!("Unexpected event"),
2002         }
2003
2004         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2005         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2006         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2007
2008         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2009         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2010         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2011
2012         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2013         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);
2014         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2015         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2016         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2017
2018         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2019         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2020 }
2021
2022 #[test]
2023 fn channel_reserve_in_flight_removes() {
2024         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2025         // can send to its counterparty, but due to update ordering, the other side may not yet have
2026         // considered those HTLCs fully removed.
2027         // This tests that we don't count HTLCs which will not be included in the next remote
2028         // commitment transaction towards the reserve value (as it implies no commitment transaction
2029         // will be generated which violates the remote reserve value).
2030         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2031         // To test this we:
2032         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2033         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2034         //    you only consider the value of the first HTLC, it may not),
2035         //  * start routing a third HTLC from A to B,
2036         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2037         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2038         //  * deliver the first fulfill from B
2039         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2040         //    claim,
2041         //  * deliver A's response CS and RAA.
2042         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2043         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2044         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2045         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2046         let chanmon_cfgs = create_chanmon_cfgs(2);
2047         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2048         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2049         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2050         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2051
2052         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2053         // Route the first two HTLCs.
2054         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2055         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2056         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2057
2058         // Start routing the third HTLC (this is just used to get everyone in the right state).
2059         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2060         let send_1 = {
2061                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2062                 check_added_monitors!(nodes[0], 1);
2063                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2064                 assert_eq!(events.len(), 1);
2065                 SendEvent::from_event(events.remove(0))
2066         };
2067
2068         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2069         // initial fulfill/CS.
2070         nodes[1].node.claim_funds(payment_preimage_1);
2071         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2072         check_added_monitors!(nodes[1], 1);
2073         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2074
2075         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2076         // remove the second HTLC when we send the HTLC back from B to A.
2077         nodes[1].node.claim_funds(payment_preimage_2);
2078         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2079         check_added_monitors!(nodes[1], 1);
2080         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2081
2082         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2083         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2084         check_added_monitors!(nodes[0], 1);
2085         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2086         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2087
2088         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2089         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2090         check_added_monitors!(nodes[1], 1);
2091         // B is already AwaitingRAA, so cant generate a CS here
2092         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2093
2094         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2095         check_added_monitors!(nodes[1], 1);
2096         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2097
2098         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2099         check_added_monitors!(nodes[0], 1);
2100         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2101
2102         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2103         check_added_monitors!(nodes[1], 1);
2104         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2105
2106         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2107         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2108         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2109         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2110         // on-chain as necessary).
2111         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2112         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2113         check_added_monitors!(nodes[0], 1);
2114         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2115         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2116
2117         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2118         check_added_monitors!(nodes[1], 1);
2119         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2120
2121         expect_pending_htlcs_forwardable!(nodes[1]);
2122         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2123
2124         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2125         // resolve the second HTLC from A's point of view.
2126         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2127         check_added_monitors!(nodes[0], 1);
2128         expect_payment_path_successful!(nodes[0]);
2129         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2130
2131         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2132         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2133         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2134         let send_2 = {
2135                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2136                 check_added_monitors!(nodes[1], 1);
2137                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2138                 assert_eq!(events.len(), 1);
2139                 SendEvent::from_event(events.remove(0))
2140         };
2141
2142         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2143         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2144         check_added_monitors!(nodes[0], 1);
2145         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2146
2147         // Now just resolve all the outstanding messages/HTLCs for completeness...
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[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2154         check_added_monitors!(nodes[1], 1);
2155
2156         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2157         check_added_monitors!(nodes[0], 1);
2158         expect_payment_path_successful!(nodes[0]);
2159         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2160
2161         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2162         check_added_monitors!(nodes[1], 1);
2163         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2164
2165         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2166         check_added_monitors!(nodes[0], 1);
2167
2168         expect_pending_htlcs_forwardable!(nodes[0]);
2169         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2170
2171         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2172         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2173 }
2174
2175 #[test]
2176 fn channel_monitor_network_test() {
2177         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2178         // tests that ChannelMonitor is able to recover from various states.
2179         let chanmon_cfgs = create_chanmon_cfgs(5);
2180         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2181         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2182         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2183
2184         // Create some initial channels
2185         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2186         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2187         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2188         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2189
2190         // Make sure all nodes are at the same starting height
2191         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2192         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2193         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2194         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2195         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2196
2197         // Rebalance the network a bit by relaying one payment through all the channels...
2198         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2199         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2200         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2201         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2202
2203         // Simple case with no pending HTLCs:
2204         nodes[1].node.force_close_channel(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2205         check_added_monitors!(nodes[1], 1);
2206         check_closed_broadcast!(nodes[1], true);
2207         {
2208                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2209                 assert_eq!(node_txn.len(), 1);
2210                 mine_transaction(&nodes[0], &node_txn[0]);
2211                 check_added_monitors!(nodes[0], 1);
2212                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2213         }
2214         check_closed_broadcast!(nodes[0], true);
2215         assert_eq!(nodes[0].node.list_channels().len(), 0);
2216         assert_eq!(nodes[1].node.list_channels().len(), 1);
2217         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2218         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2219
2220         // One pending HTLC is discarded by the force-close:
2221         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2222
2223         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2224         // broadcasted until we reach the timelock time).
2225         nodes[1].node.force_close_channel(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2226         check_closed_broadcast!(nodes[1], true);
2227         check_added_monitors!(nodes[1], 1);
2228         {
2229                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2230                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2231                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2232                 mine_transaction(&nodes[2], &node_txn[0]);
2233                 check_added_monitors!(nodes[2], 1);
2234                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2235         }
2236         check_closed_broadcast!(nodes[2], true);
2237         assert_eq!(nodes[1].node.list_channels().len(), 0);
2238         assert_eq!(nodes[2].node.list_channels().len(), 1);
2239         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2240         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2241
2242         macro_rules! claim_funds {
2243                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2244                         {
2245                                 $node.node.claim_funds($preimage);
2246                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2247                                 check_added_monitors!($node, 1);
2248
2249                                 let events = $node.node.get_and_clear_pending_msg_events();
2250                                 assert_eq!(events.len(), 1);
2251                                 match events[0] {
2252                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2253                                                 assert!(update_add_htlcs.is_empty());
2254                                                 assert!(update_fail_htlcs.is_empty());
2255                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2256                                         },
2257                                         _ => panic!("Unexpected event"),
2258                                 };
2259                         }
2260                 }
2261         }
2262
2263         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2264         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2265         nodes[2].node.force_close_channel(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2266         check_added_monitors!(nodes[2], 1);
2267         check_closed_broadcast!(nodes[2], true);
2268         let node2_commitment_txid;
2269         {
2270                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2271                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2272                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2273                 node2_commitment_txid = node_txn[0].txid();
2274
2275                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2276                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2277                 mine_transaction(&nodes[3], &node_txn[0]);
2278                 check_added_monitors!(nodes[3], 1);
2279                 check_preimage_claim(&nodes[3], &node_txn);
2280         }
2281         check_closed_broadcast!(nodes[3], true);
2282         assert_eq!(nodes[2].node.list_channels().len(), 0);
2283         assert_eq!(nodes[3].node.list_channels().len(), 1);
2284         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2285         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2286
2287         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2288         // confusing us in the following tests.
2289         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2290
2291         // One pending HTLC to time out:
2292         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2293         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2294         // buffer space).
2295
2296         let (close_chan_update_1, close_chan_update_2) = {
2297                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2298                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2299                 assert_eq!(events.len(), 2);
2300                 let close_chan_update_1 = match events[0] {
2301                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2302                                 msg.clone()
2303                         },
2304                         _ => panic!("Unexpected event"),
2305                 };
2306                 match events[1] {
2307                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2308                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2309                         },
2310                         _ => panic!("Unexpected event"),
2311                 }
2312                 check_added_monitors!(nodes[3], 1);
2313
2314                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2315                 {
2316                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2317                         node_txn.retain(|tx| {
2318                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2319                                         false
2320                                 } else { true }
2321                         });
2322                 }
2323
2324                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2325
2326                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2327                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2328
2329                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2330                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2331                 assert_eq!(events.len(), 2);
2332                 let close_chan_update_2 = match events[0] {
2333                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2334                                 msg.clone()
2335                         },
2336                         _ => panic!("Unexpected event"),
2337                 };
2338                 match events[1] {
2339                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2340                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2341                         },
2342                         _ => panic!("Unexpected event"),
2343                 }
2344                 check_added_monitors!(nodes[4], 1);
2345                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2346
2347                 mine_transaction(&nodes[4], &node_txn[0]);
2348                 check_preimage_claim(&nodes[4], &node_txn);
2349                 (close_chan_update_1, close_chan_update_2)
2350         };
2351         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2352         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2353         assert_eq!(nodes[3].node.list_channels().len(), 0);
2354         assert_eq!(nodes[4].node.list_channels().len(), 0);
2355
2356         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2357         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2358         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2359 }
2360
2361 #[test]
2362 fn test_justice_tx() {
2363         // Test justice txn built on revoked HTLC-Success tx, against both sides
2364         let mut alice_config = UserConfig::default();
2365         alice_config.own_channel_config.announced_channel = true;
2366         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2367         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2368         let mut bob_config = UserConfig::default();
2369         bob_config.own_channel_config.announced_channel = true;
2370         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2371         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2372         let user_cfgs = [Some(alice_config), Some(bob_config)];
2373         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2374         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2375         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2376         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2377         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2378         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2379         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2380         // Create some new channels:
2381         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2382
2383         // A pending HTLC which will be revoked:
2384         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2385         // Get the will-be-revoked local txn from nodes[0]
2386         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2387         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2388         assert_eq!(revoked_local_txn[0].input.len(), 1);
2389         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2390         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2391         assert_eq!(revoked_local_txn[1].input.len(), 1);
2392         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2393         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2394         // Revoke the old state
2395         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2396
2397         {
2398                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2399                 {
2400                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2401                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2402                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2403
2404                         check_spends!(node_txn[0], revoked_local_txn[0]);
2405                         node_txn.swap_remove(0);
2406                         node_txn.truncate(1);
2407                 }
2408                 check_added_monitors!(nodes[1], 1);
2409                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2410                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2411
2412                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2413                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2414                 // Verify broadcast of revoked HTLC-timeout
2415                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2416                 check_added_monitors!(nodes[0], 1);
2417                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2418                 // Broadcast revoked HTLC-timeout on node 1
2419                 mine_transaction(&nodes[1], &node_txn[1]);
2420                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2421         }
2422         get_announce_close_broadcast_events(&nodes, 0, 1);
2423
2424         assert_eq!(nodes[0].node.list_channels().len(), 0);
2425         assert_eq!(nodes[1].node.list_channels().len(), 0);
2426
2427         // We test justice_tx build by A on B's revoked HTLC-Success tx
2428         // Create some new channels:
2429         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2430         {
2431                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2432                 node_txn.clear();
2433         }
2434
2435         // A pending HTLC which will be revoked:
2436         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2437         // Get the will-be-revoked local txn from B
2438         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2439         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2440         assert_eq!(revoked_local_txn[0].input.len(), 1);
2441         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2442         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2443         // Revoke the old state
2444         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2445         {
2446                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2447                 {
2448                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2449                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2450                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2451
2452                         check_spends!(node_txn[0], revoked_local_txn[0]);
2453                         node_txn.swap_remove(0);
2454                 }
2455                 check_added_monitors!(nodes[0], 1);
2456                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2457
2458                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2459                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2460                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2461                 check_added_monitors!(nodes[1], 1);
2462                 mine_transaction(&nodes[0], &node_txn[1]);
2463                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2464                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2465         }
2466         get_announce_close_broadcast_events(&nodes, 0, 1);
2467         assert_eq!(nodes[0].node.list_channels().len(), 0);
2468         assert_eq!(nodes[1].node.list_channels().len(), 0);
2469 }
2470
2471 #[test]
2472 fn revoked_output_claim() {
2473         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2474         // transaction is broadcast by its counterparty
2475         let chanmon_cfgs = create_chanmon_cfgs(2);
2476         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2477         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2478         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2479         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2480         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2481         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2482         assert_eq!(revoked_local_txn.len(), 1);
2483         // Only output is the full channel value back to nodes[0]:
2484         assert_eq!(revoked_local_txn[0].output.len(), 1);
2485         // Send a payment through, updating everyone's latest commitment txn
2486         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2487
2488         // Inform nodes[1] that nodes[0] broadcast a stale tx
2489         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2490         check_added_monitors!(nodes[1], 1);
2491         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2492         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2493         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2494
2495         check_spends!(node_txn[0], revoked_local_txn[0]);
2496         check_spends!(node_txn[1], chan_1.3);
2497
2498         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2499         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2500         get_announce_close_broadcast_events(&nodes, 0, 1);
2501         check_added_monitors!(nodes[0], 1);
2502         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2503 }
2504
2505 #[test]
2506 fn claim_htlc_outputs_shared_tx() {
2507         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2508         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2509         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2510         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2511         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2512         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2513
2514         // Create some new channel:
2515         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2516
2517         // Rebalance the network to generate htlc in the two directions
2518         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2519         // 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
2520         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2521         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2522
2523         // Get the will-be-revoked local txn from node[0]
2524         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2525         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2526         assert_eq!(revoked_local_txn[0].input.len(), 1);
2527         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2528         assert_eq!(revoked_local_txn[1].input.len(), 1);
2529         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2530         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2531         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2532
2533         //Revoke the old state
2534         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2535
2536         {
2537                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2538                 check_added_monitors!(nodes[0], 1);
2539                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2540                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2541                 check_added_monitors!(nodes[1], 1);
2542                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2543                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2544                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2545
2546                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2547                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2548
2549                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2550                 check_spends!(node_txn[0], revoked_local_txn[0]);
2551
2552                 let mut witness_lens = BTreeSet::new();
2553                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2554                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2555                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2556                 assert_eq!(witness_lens.len(), 3);
2557                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2558                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2559                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2560
2561                 // Next nodes[1] broadcasts its current local tx state:
2562                 assert_eq!(node_txn[1].input.len(), 1);
2563                 check_spends!(node_txn[1], chan_1.3);
2564
2565                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2566                 // ANTI_REORG_DELAY confirmations.
2567                 mine_transaction(&nodes[1], &node_txn[0]);
2568                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2569                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2570         }
2571         get_announce_close_broadcast_events(&nodes, 0, 1);
2572         assert_eq!(nodes[0].node.list_channels().len(), 0);
2573         assert_eq!(nodes[1].node.list_channels().len(), 0);
2574 }
2575
2576 #[test]
2577 fn claim_htlc_outputs_single_tx() {
2578         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2579         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2580         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2581         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2582         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2583         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2584
2585         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2586
2587         // Rebalance the network to generate htlc in the two directions
2588         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2589         // 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
2590         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2591         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2592         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2593
2594         // Get the will-be-revoked local txn from node[0]
2595         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2596
2597         //Revoke the old state
2598         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2599
2600         {
2601                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2602                 check_added_monitors!(nodes[0], 1);
2603                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2604                 check_added_monitors!(nodes[1], 1);
2605                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2606                 let mut events = nodes[0].node.get_and_clear_pending_events();
2607                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2608                 match events[1] {
2609                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2610                         _ => panic!("Unexpected event"),
2611                 }
2612
2613                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2614                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2615
2616                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2617                 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2618
2619                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2620                 assert_eq!(node_txn[0].input.len(), 1);
2621                 check_spends!(node_txn[0], chan_1.3);
2622                 assert_eq!(node_txn[1].input.len(), 1);
2623                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2624                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2625                 check_spends!(node_txn[1], node_txn[0]);
2626
2627                 // Justice transactions are indices 1-2-4
2628                 assert_eq!(node_txn[2].input.len(), 1);
2629                 assert_eq!(node_txn[3].input.len(), 1);
2630                 assert_eq!(node_txn[4].input.len(), 1);
2631
2632                 check_spends!(node_txn[2], revoked_local_txn[0]);
2633                 check_spends!(node_txn[3], revoked_local_txn[0]);
2634                 check_spends!(node_txn[4], revoked_local_txn[0]);
2635
2636                 let mut witness_lens = BTreeSet::new();
2637                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2638                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2639                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2640                 assert_eq!(witness_lens.len(), 3);
2641                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2642                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2643                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2644
2645                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2646                 // ANTI_REORG_DELAY confirmations.
2647                 mine_transaction(&nodes[1], &node_txn[2]);
2648                 mine_transaction(&nodes[1], &node_txn[3]);
2649                 mine_transaction(&nodes[1], &node_txn[4]);
2650                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2651                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2652         }
2653         get_announce_close_broadcast_events(&nodes, 0, 1);
2654         assert_eq!(nodes[0].node.list_channels().len(), 0);
2655         assert_eq!(nodes[1].node.list_channels().len(), 0);
2656 }
2657
2658 #[test]
2659 fn test_htlc_on_chain_success() {
2660         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2661         // the preimage backward accordingly. So here we test that ChannelManager is
2662         // broadcasting the right event to other nodes in payment path.
2663         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2664         // A --------------------> B ----------------------> C (preimage)
2665         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2666         // commitment transaction was broadcast.
2667         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2668         // towards B.
2669         // B should be able to claim via preimage if A then broadcasts its local tx.
2670         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2671         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2672         // PaymentSent event).
2673
2674         let chanmon_cfgs = create_chanmon_cfgs(3);
2675         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2676         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2677         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2678
2679         // Create some initial channels
2680         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2681         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2682
2683         // Ensure all nodes are at the same height
2684         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2685         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2686         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2687         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2688
2689         // Rebalance the network a bit by relaying one payment through all the channels...
2690         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2691         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2692
2693         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2694         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2695
2696         // Broadcast legit commitment tx from C on B's chain
2697         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2698         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2699         assert_eq!(commitment_tx.len(), 1);
2700         check_spends!(commitment_tx[0], chan_2.3);
2701         nodes[2].node.claim_funds(our_payment_preimage);
2702         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2703         nodes[2].node.claim_funds(our_payment_preimage_2);
2704         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2705         check_added_monitors!(nodes[2], 2);
2706         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2707         assert!(updates.update_add_htlcs.is_empty());
2708         assert!(updates.update_fail_htlcs.is_empty());
2709         assert!(updates.update_fail_malformed_htlcs.is_empty());
2710         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2711
2712         mine_transaction(&nodes[2], &commitment_tx[0]);
2713         check_closed_broadcast!(nodes[2], true);
2714         check_added_monitors!(nodes[2], 1);
2715         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2716         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)
2717         assert_eq!(node_txn.len(), 5);
2718         assert_eq!(node_txn[0], node_txn[3]);
2719         assert_eq!(node_txn[1], node_txn[4]);
2720         assert_eq!(node_txn[2], commitment_tx[0]);
2721         check_spends!(node_txn[0], commitment_tx[0]);
2722         check_spends!(node_txn[1], commitment_tx[0]);
2723         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2724         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2725         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2726         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2727         assert_eq!(node_txn[0].lock_time, 0);
2728         assert_eq!(node_txn[1].lock_time, 0);
2729
2730         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2731         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2732         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2733         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2734         {
2735                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2736                 assert_eq!(added_monitors.len(), 1);
2737                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2738                 added_monitors.clear();
2739         }
2740         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2741         assert_eq!(forwarded_events.len(), 3);
2742         match forwarded_events[0] {
2743                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2744                 _ => panic!("Unexpected event"),
2745         }
2746         let chan_id = Some(chan_1.2);
2747         match forwarded_events[1] {
2748                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2749                         assert_eq!(fee_earned_msat, Some(1000));
2750                         assert_eq!(prev_channel_id, chan_id);
2751                         assert_eq!(claim_from_onchain_tx, true);
2752                         assert_eq!(next_channel_id, Some(chan_2.2));
2753                 },
2754                 _ => panic!()
2755         }
2756         match forwarded_events[2] {
2757                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2758                         assert_eq!(fee_earned_msat, Some(1000));
2759                         assert_eq!(prev_channel_id, chan_id);
2760                         assert_eq!(claim_from_onchain_tx, true);
2761                         assert_eq!(next_channel_id, Some(chan_2.2));
2762                 },
2763                 _ => panic!()
2764         }
2765         let events = nodes[1].node.get_and_clear_pending_msg_events();
2766         {
2767                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2768                 assert_eq!(added_monitors.len(), 2);
2769                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2770                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2771                 added_monitors.clear();
2772         }
2773         assert_eq!(events.len(), 3);
2774         match events[0] {
2775                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2776                 _ => panic!("Unexpected event"),
2777         }
2778         match events[1] {
2779                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2780                 _ => panic!("Unexpected event"),
2781         }
2782
2783         match events[2] {
2784                 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, .. } } => {
2785                         assert!(update_add_htlcs.is_empty());
2786                         assert!(update_fail_htlcs.is_empty());
2787                         assert_eq!(update_fulfill_htlcs.len(), 1);
2788                         assert!(update_fail_malformed_htlcs.is_empty());
2789                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2790                 },
2791                 _ => panic!("Unexpected event"),
2792         };
2793         macro_rules! check_tx_local_broadcast {
2794                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2795                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2796                         assert_eq!(node_txn.len(), 3);
2797                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2798                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2799                         check_spends!(node_txn[1], $commitment_tx);
2800                         check_spends!(node_txn[2], $commitment_tx);
2801                         assert_ne!(node_txn[1].lock_time, 0);
2802                         assert_ne!(node_txn[2].lock_time, 0);
2803                         if $htlc_offered {
2804                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2805                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2806                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2807                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2808                         } else {
2809                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2810                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2811                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2812                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2813                         }
2814                         check_spends!(node_txn[0], $chan_tx);
2815                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2816                         node_txn.clear();
2817                 } }
2818         }
2819         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2820         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2821         // timeout-claim of the output that nodes[2] just claimed via success.
2822         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2823
2824         // Broadcast legit commitment tx from A on B's chain
2825         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2826         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2827         check_spends!(node_a_commitment_tx[0], chan_1.3);
2828         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2829         check_closed_broadcast!(nodes[1], true);
2830         check_added_monitors!(nodes[1], 1);
2831         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2832         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2833         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2834         let commitment_spend =
2835                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2836                         check_spends!(node_txn[1], commitment_tx[0]);
2837                         check_spends!(node_txn[2], commitment_tx[0]);
2838                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2839                         &node_txn[0]
2840                 } else {
2841                         check_spends!(node_txn[0], commitment_tx[0]);
2842                         check_spends!(node_txn[1], commitment_tx[0]);
2843                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2844                         &node_txn[2]
2845                 };
2846
2847         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2848         assert_eq!(commitment_spend.input.len(), 2);
2849         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2850         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2851         assert_eq!(commitment_spend.lock_time, 0);
2852         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2853         check_spends!(node_txn[3], chan_1.3);
2854         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2855         check_spends!(node_txn[4], node_txn[3]);
2856         check_spends!(node_txn[5], node_txn[3]);
2857         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2858         // we already checked the same situation with A.
2859
2860         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2861         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2862         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2863         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2864         check_closed_broadcast!(nodes[0], true);
2865         check_added_monitors!(nodes[0], 1);
2866         let events = nodes[0].node.get_and_clear_pending_events();
2867         assert_eq!(events.len(), 5);
2868         let mut first_claimed = false;
2869         for event in events {
2870                 match event {
2871                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2872                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2873                                         assert!(!first_claimed);
2874                                         first_claimed = true;
2875                                 } else {
2876                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2877                                         assert_eq!(payment_hash, payment_hash_2);
2878                                 }
2879                         },
2880                         Event::PaymentPathSuccessful { .. } => {},
2881                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2882                         _ => panic!("Unexpected event"),
2883                 }
2884         }
2885         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2886 }
2887
2888 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2889         // Test that in case of a unilateral close onchain, we detect the state of output and
2890         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2891         // broadcasting the right event to other nodes in payment path.
2892         // A ------------------> B ----------------------> C (timeout)
2893         //    B's commitment tx                 C's commitment tx
2894         //            \                                  \
2895         //         B's HTLC timeout tx               B's timeout tx
2896
2897         let chanmon_cfgs = create_chanmon_cfgs(3);
2898         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2899         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2900         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2901         *nodes[0].connect_style.borrow_mut() = connect_style;
2902         *nodes[1].connect_style.borrow_mut() = connect_style;
2903         *nodes[2].connect_style.borrow_mut() = connect_style;
2904
2905         // Create some intial channels
2906         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2907         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2908
2909         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2910         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2911         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2912
2913         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2914
2915         // Broadcast legit commitment tx from C on B's chain
2916         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2917         check_spends!(commitment_tx[0], chan_2.3);
2918         nodes[2].node.fail_htlc_backwards(&payment_hash);
2919         check_added_monitors!(nodes[2], 0);
2920         expect_pending_htlcs_forwardable!(nodes[2]);
2921         check_added_monitors!(nodes[2], 1);
2922
2923         let events = nodes[2].node.get_and_clear_pending_msg_events();
2924         assert_eq!(events.len(), 1);
2925         match events[0] {
2926                 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, .. } } => {
2927                         assert!(update_add_htlcs.is_empty());
2928                         assert!(!update_fail_htlcs.is_empty());
2929                         assert!(update_fulfill_htlcs.is_empty());
2930                         assert!(update_fail_malformed_htlcs.is_empty());
2931                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2932                 },
2933                 _ => panic!("Unexpected event"),
2934         };
2935         mine_transaction(&nodes[2], &commitment_tx[0]);
2936         check_closed_broadcast!(nodes[2], true);
2937         check_added_monitors!(nodes[2], 1);
2938         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2939         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2940         assert_eq!(node_txn.len(), 1);
2941         check_spends!(node_txn[0], chan_2.3);
2942         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2943
2944         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2945         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2946         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2947         mine_transaction(&nodes[1], &commitment_tx[0]);
2948         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2949         let timeout_tx;
2950         {
2951                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2952                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2953                 assert_eq!(node_txn[0], node_txn[3]);
2954                 assert_eq!(node_txn[1], node_txn[4]);
2955
2956                 check_spends!(node_txn[2], commitment_tx[0]);
2957                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2958
2959                 check_spends!(node_txn[0], chan_2.3);
2960                 check_spends!(node_txn[1], node_txn[0]);
2961                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2962                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2963
2964                 timeout_tx = node_txn[2].clone();
2965                 node_txn.clear();
2966         }
2967
2968         mine_transaction(&nodes[1], &timeout_tx);
2969         check_added_monitors!(nodes[1], 1);
2970         check_closed_broadcast!(nodes[1], true);
2971         {
2972                 // B will rebroadcast a fee-bumped timeout transaction here.
2973                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2974                 assert_eq!(node_txn.len(), 1);
2975                 check_spends!(node_txn[0], commitment_tx[0]);
2976         }
2977
2978         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2979         {
2980                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2981                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2982                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2983                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2984                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2985                 if node_txn.len() == 1 {
2986                         check_spends!(node_txn[0], chan_2.3);
2987                 } else {
2988                         assert_eq!(node_txn.len(), 0);
2989                 }
2990         }
2991
2992         expect_pending_htlcs_forwardable!(nodes[1]);
2993         check_added_monitors!(nodes[1], 1);
2994         let events = nodes[1].node.get_and_clear_pending_msg_events();
2995         assert_eq!(events.len(), 1);
2996         match events[0] {
2997                 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, .. } } => {
2998                         assert!(update_add_htlcs.is_empty());
2999                         assert!(!update_fail_htlcs.is_empty());
3000                         assert!(update_fulfill_htlcs.is_empty());
3001                         assert!(update_fail_malformed_htlcs.is_empty());
3002                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3003                 },
3004                 _ => panic!("Unexpected event"),
3005         };
3006
3007         // Broadcast legit commitment tx from B on A's chain
3008         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3009         check_spends!(commitment_tx[0], chan_1.3);
3010
3011         mine_transaction(&nodes[0], &commitment_tx[0]);
3012         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3013
3014         check_closed_broadcast!(nodes[0], true);
3015         check_added_monitors!(nodes[0], 1);
3016         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3017         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3018         assert_eq!(node_txn.len(), 2);
3019         check_spends!(node_txn[0], chan_1.3);
3020         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3021         check_spends!(node_txn[1], commitment_tx[0]);
3022         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3023 }
3024
3025 #[test]
3026 fn test_htlc_on_chain_timeout() {
3027         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3028         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3029         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3030 }
3031
3032 #[test]
3033 fn test_simple_commitment_revoked_fail_backward() {
3034         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3035         // and fail backward accordingly.
3036
3037         let chanmon_cfgs = create_chanmon_cfgs(3);
3038         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3039         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3040         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3041
3042         // Create some initial channels
3043         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3044         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3045
3046         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3047         // Get the will-be-revoked local txn from nodes[2]
3048         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3049         // Revoke the old state
3050         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3051
3052         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3053
3054         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3055         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3056         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3057         check_added_monitors!(nodes[1], 1);
3058         check_closed_broadcast!(nodes[1], true);
3059
3060         expect_pending_htlcs_forwardable!(nodes[1]);
3061         check_added_monitors!(nodes[1], 1);
3062         let events = nodes[1].node.get_and_clear_pending_msg_events();
3063         assert_eq!(events.len(), 1);
3064         match events[0] {
3065                 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, .. } } => {
3066                         assert!(update_add_htlcs.is_empty());
3067                         assert_eq!(update_fail_htlcs.len(), 1);
3068                         assert!(update_fulfill_htlcs.is_empty());
3069                         assert!(update_fail_malformed_htlcs.is_empty());
3070                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3071
3072                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3073                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3074                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3075                 },
3076                 _ => panic!("Unexpected event"),
3077         }
3078 }
3079
3080 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3081         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3082         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3083         // commitment transaction anymore.
3084         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3085         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3086         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3087         // technically disallowed and we should probably handle it reasonably.
3088         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3089         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3090         // transactions:
3091         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3092         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3093         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3094         //   and once they revoke the previous commitment transaction (allowing us to send a new
3095         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3096         let chanmon_cfgs = create_chanmon_cfgs(3);
3097         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3098         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3099         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3100
3101         // Create some initial channels
3102         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3103         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3104
3105         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 });
3106         // Get the will-be-revoked local txn from nodes[2]
3107         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3108         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3109         // Revoke the old state
3110         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3111
3112         let value = if use_dust {
3113                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3114                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3115                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3116         } else { 3000000 };
3117
3118         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3119         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3120         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3121
3122         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3123         expect_pending_htlcs_forwardable!(nodes[2]);
3124         check_added_monitors!(nodes[2], 1);
3125         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3126         assert!(updates.update_add_htlcs.is_empty());
3127         assert!(updates.update_fulfill_htlcs.is_empty());
3128         assert!(updates.update_fail_malformed_htlcs.is_empty());
3129         assert_eq!(updates.update_fail_htlcs.len(), 1);
3130         assert!(updates.update_fee.is_none());
3131         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3132         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3133         // Drop the last RAA from 3 -> 2
3134
3135         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3136         expect_pending_htlcs_forwardable!(nodes[2]);
3137         check_added_monitors!(nodes[2], 1);
3138         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3139         assert!(updates.update_add_htlcs.is_empty());
3140         assert!(updates.update_fulfill_htlcs.is_empty());
3141         assert!(updates.update_fail_malformed_htlcs.is_empty());
3142         assert_eq!(updates.update_fail_htlcs.len(), 1);
3143         assert!(updates.update_fee.is_none());
3144         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3145         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3146         check_added_monitors!(nodes[1], 1);
3147         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3148         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3149         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3150         check_added_monitors!(nodes[2], 1);
3151
3152         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3153         expect_pending_htlcs_forwardable!(nodes[2]);
3154         check_added_monitors!(nodes[2], 1);
3155         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3156         assert!(updates.update_add_htlcs.is_empty());
3157         assert!(updates.update_fulfill_htlcs.is_empty());
3158         assert!(updates.update_fail_malformed_htlcs.is_empty());
3159         assert_eq!(updates.update_fail_htlcs.len(), 1);
3160         assert!(updates.update_fee.is_none());
3161         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3162         // At this point first_payment_hash has dropped out of the latest two commitment
3163         // transactions that nodes[1] is tracking...
3164         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3165         check_added_monitors!(nodes[1], 1);
3166         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3167         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3168         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3169         check_added_monitors!(nodes[2], 1);
3170
3171         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3172         // on nodes[2]'s RAA.
3173         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3174         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3175         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3176         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3177         check_added_monitors!(nodes[1], 0);
3178
3179         if deliver_bs_raa {
3180                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3181                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3182                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3183                 check_added_monitors!(nodes[1], 1);
3184                 let events = nodes[1].node.get_and_clear_pending_events();
3185                 assert_eq!(events.len(), 1);
3186                 match events[0] {
3187                         Event::PendingHTLCsForwardable { .. } => { },
3188                         _ => panic!("Unexpected event"),
3189                 };
3190                 // Deliberately don't process the pending fail-back so they all fail back at once after
3191                 // block connection just like the !deliver_bs_raa case
3192         }
3193
3194         let mut failed_htlcs = HashSet::new();
3195         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3196
3197         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3198         check_added_monitors!(nodes[1], 1);
3199         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3200         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3201
3202         let events = nodes[1].node.get_and_clear_pending_events();
3203         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3204         match events[0] {
3205                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3206                 _ => panic!("Unexepected event"),
3207         }
3208         match events[1] {
3209                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3210                         assert_eq!(*payment_hash, fourth_payment_hash);
3211                 },
3212                 _ => panic!("Unexpected event"),
3213         }
3214         if !deliver_bs_raa {
3215                 match events[2] {
3216                         Event::PaymentFailed { ref payment_hash, .. } => {
3217                                 assert_eq!(*payment_hash, fourth_payment_hash);
3218                         },
3219                         _ => panic!("Unexpected event"),
3220                 }
3221                 match events[3] {
3222                         Event::PendingHTLCsForwardable { .. } => { },
3223                         _ => panic!("Unexpected event"),
3224                 };
3225         }
3226         nodes[1].node.process_pending_htlc_forwards();
3227         check_added_monitors!(nodes[1], 1);
3228
3229         let events = nodes[1].node.get_and_clear_pending_msg_events();
3230         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3231         match events[if deliver_bs_raa { 1 } else { 0 }] {
3232                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3233                 _ => panic!("Unexpected event"),
3234         }
3235         match events[if deliver_bs_raa { 2 } else { 1 }] {
3236                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3237                         assert_eq!(channel_id, chan_2.2);
3238                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3239                 },
3240                 _ => panic!("Unexpected event"),
3241         }
3242         if deliver_bs_raa {
3243                 match events[0] {
3244                         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, .. } } => {
3245                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3246                                 assert_eq!(update_add_htlcs.len(), 1);
3247                                 assert!(update_fulfill_htlcs.is_empty());
3248                                 assert!(update_fail_htlcs.is_empty());
3249                                 assert!(update_fail_malformed_htlcs.is_empty());
3250                         },
3251                         _ => panic!("Unexpected event"),
3252                 }
3253         }
3254         match events[if deliver_bs_raa { 3 } else { 2 }] {
3255                 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, .. } } => {
3256                         assert!(update_add_htlcs.is_empty());
3257                         assert_eq!(update_fail_htlcs.len(), 3);
3258                         assert!(update_fulfill_htlcs.is_empty());
3259                         assert!(update_fail_malformed_htlcs.is_empty());
3260                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3261
3262                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3263                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3264                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3265
3266                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3267
3268                         let events = nodes[0].node.get_and_clear_pending_events();
3269                         assert_eq!(events.len(), 3);
3270                         match events[0] {
3271                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3272                                         assert!(failed_htlcs.insert(payment_hash.0));
3273                                         // If we delivered B's RAA we got an unknown preimage error, not something
3274                                         // that we should update our routing table for.
3275                                         if !deliver_bs_raa {
3276                                                 assert!(network_update.is_some());
3277                                         }
3278                                 },
3279                                 _ => panic!("Unexpected event"),
3280                         }
3281                         match events[1] {
3282                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3283                                         assert!(failed_htlcs.insert(payment_hash.0));
3284                                         assert!(network_update.is_some());
3285                                 },
3286                                 _ => panic!("Unexpected event"),
3287                         }
3288                         match events[2] {
3289                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3290                                         assert!(failed_htlcs.insert(payment_hash.0));
3291                                         assert!(network_update.is_some());
3292                                 },
3293                                 _ => panic!("Unexpected event"),
3294                         }
3295                 },
3296                 _ => panic!("Unexpected event"),
3297         }
3298
3299         assert!(failed_htlcs.contains(&first_payment_hash.0));
3300         assert!(failed_htlcs.contains(&second_payment_hash.0));
3301         assert!(failed_htlcs.contains(&third_payment_hash.0));
3302 }
3303
3304 #[test]
3305 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3306         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3307         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3308         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3309         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3310 }
3311
3312 #[test]
3313 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3314         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3315         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3316         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3317         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3318 }
3319
3320 #[test]
3321 fn fail_backward_pending_htlc_upon_channel_failure() {
3322         let chanmon_cfgs = create_chanmon_cfgs(2);
3323         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3324         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3325         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3326         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3327
3328         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3329         {
3330                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3331                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3332                 check_added_monitors!(nodes[0], 1);
3333
3334                 let payment_event = {
3335                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3336                         assert_eq!(events.len(), 1);
3337                         SendEvent::from_event(events.remove(0))
3338                 };
3339                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3340                 assert_eq!(payment_event.msgs.len(), 1);
3341         }
3342
3343         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3344         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3345         {
3346                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3347                 check_added_monitors!(nodes[0], 0);
3348
3349                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3350         }
3351
3352         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3353         {
3354                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3355
3356                 let secp_ctx = Secp256k1::new();
3357                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3358                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3359                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3360                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3361                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3362
3363                 // Send a 0-msat update_add_htlc to fail the channel.
3364                 let update_add_htlc = msgs::UpdateAddHTLC {
3365                         channel_id: chan.2,
3366                         htlc_id: 0,
3367                         amount_msat: 0,
3368                         payment_hash,
3369                         cltv_expiry,
3370                         onion_routing_packet,
3371                 };
3372                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3373         }
3374         let events = nodes[0].node.get_and_clear_pending_events();
3375         assert_eq!(events.len(), 2);
3376         // Check that Alice fails backward the pending HTLC from the second payment.
3377         match events[0] {
3378                 Event::PaymentPathFailed { payment_hash, .. } => {
3379                         assert_eq!(payment_hash, failed_payment_hash);
3380                 },
3381                 _ => panic!("Unexpected event"),
3382         }
3383         match events[1] {
3384                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3385                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3386                 },
3387                 _ => panic!("Unexpected event {:?}", events[1]),
3388         }
3389         check_closed_broadcast!(nodes[0], true);
3390         check_added_monitors!(nodes[0], 1);
3391 }
3392
3393 #[test]
3394 fn test_htlc_ignore_latest_remote_commitment() {
3395         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3396         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3397         let chanmon_cfgs = create_chanmon_cfgs(2);
3398         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3399         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3400         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3401         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3402
3403         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3404         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3405         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3406         check_closed_broadcast!(nodes[0], true);
3407         check_added_monitors!(nodes[0], 1);
3408         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3409
3410         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3411         assert_eq!(node_txn.len(), 3);
3412         assert_eq!(node_txn[0], node_txn[1]);
3413
3414         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3415         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3416         check_closed_broadcast!(nodes[1], true);
3417         check_added_monitors!(nodes[1], 1);
3418         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3419
3420         // Duplicate the connect_block call since this may happen due to other listeners
3421         // registering new transactions
3422         header.prev_blockhash = header.block_hash();
3423         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3424 }
3425
3426 #[test]
3427 fn test_force_close_fail_back() {
3428         // Check which HTLCs are failed-backwards on channel force-closure
3429         let chanmon_cfgs = create_chanmon_cfgs(3);
3430         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3431         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3432         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3433         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3434         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3435
3436         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3437
3438         let mut payment_event = {
3439                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3440                 check_added_monitors!(nodes[0], 1);
3441
3442                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3443                 assert_eq!(events.len(), 1);
3444                 SendEvent::from_event(events.remove(0))
3445         };
3446
3447         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3448         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3449
3450         expect_pending_htlcs_forwardable!(nodes[1]);
3451
3452         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3453         assert_eq!(events_2.len(), 1);
3454         payment_event = SendEvent::from_event(events_2.remove(0));
3455         assert_eq!(payment_event.msgs.len(), 1);
3456
3457         check_added_monitors!(nodes[1], 1);
3458         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3459         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3460         check_added_monitors!(nodes[2], 1);
3461         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3462
3463         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3464         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3465         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3466
3467         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3468         check_closed_broadcast!(nodes[2], true);
3469         check_added_monitors!(nodes[2], 1);
3470         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3471         let tx = {
3472                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3473                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3474                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3475                 // back to nodes[1] upon timeout otherwise.
3476                 assert_eq!(node_txn.len(), 1);
3477                 node_txn.remove(0)
3478         };
3479
3480         mine_transaction(&nodes[1], &tx);
3481
3482         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3483         check_closed_broadcast!(nodes[1], true);
3484         check_added_monitors!(nodes[1], 1);
3485         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3486
3487         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3488         {
3489                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3490                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3491         }
3492         mine_transaction(&nodes[2], &tx);
3493         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3494         assert_eq!(node_txn.len(), 1);
3495         assert_eq!(node_txn[0].input.len(), 1);
3496         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3497         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3498         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3499
3500         check_spends!(node_txn[0], tx);
3501 }
3502
3503 #[test]
3504 fn test_dup_events_on_peer_disconnect() {
3505         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3506         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3507         // as we used to generate the event immediately upon receipt of the payment preimage in the
3508         // update_fulfill_htlc message.
3509
3510         let chanmon_cfgs = create_chanmon_cfgs(2);
3511         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3512         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3513         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3514         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3515
3516         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3517
3518         nodes[1].node.claim_funds(payment_preimage);
3519         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3520         check_added_monitors!(nodes[1], 1);
3521         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3522         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3523         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3524
3525         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3526         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3527
3528         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3529         expect_payment_path_successful!(nodes[0]);
3530 }
3531
3532 #[test]
3533 fn test_peer_disconnected_before_funding_broadcasted() {
3534         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3535         // before the funding transaction has been broadcasted.
3536         let chanmon_cfgs = create_chanmon_cfgs(2);
3537         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3538         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3539         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3540
3541         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3542         // broadcasted, even though it's created by `nodes[0]`.
3543         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();
3544         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3545         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3546         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3547         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3548
3549         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3550         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3551
3552         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3553
3554         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3555         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3556
3557         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3558         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3559         // broadcasted.
3560         {
3561                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3562         }
3563
3564         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3565         // disconnected before the funding transaction was broadcasted.
3566         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3567         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3568
3569         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3570         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3571 }
3572
3573 #[test]
3574 fn test_simple_peer_disconnect() {
3575         // Test that we can reconnect when there are no lost messages
3576         let chanmon_cfgs = create_chanmon_cfgs(3);
3577         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3578         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3579         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3580         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3581         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3582
3583         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3584         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3585         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3586
3587         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3588         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3589         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3590         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3591
3592         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3593         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3594         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3595
3596         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3597         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3598         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3599         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3600
3601         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3602         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3603
3604         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3605         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3606
3607         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3608         {
3609                 let events = nodes[0].node.get_and_clear_pending_events();
3610                 assert_eq!(events.len(), 3);
3611                 match events[0] {
3612                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3613                                 assert_eq!(payment_preimage, payment_preimage_3);
3614                                 assert_eq!(payment_hash, payment_hash_3);
3615                         },
3616                         _ => panic!("Unexpected event"),
3617                 }
3618                 match events[1] {
3619                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3620                                 assert_eq!(payment_hash, payment_hash_5);
3621                                 assert!(rejected_by_dest);
3622                         },
3623                         _ => panic!("Unexpected event"),
3624                 }
3625                 match events[2] {
3626                         Event::PaymentPathSuccessful { .. } => {},
3627                         _ => panic!("Unexpected event"),
3628                 }
3629         }
3630
3631         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3632         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3633 }
3634
3635 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3636         // Test that we can reconnect when in-flight HTLC updates get dropped
3637         let chanmon_cfgs = create_chanmon_cfgs(2);
3638         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3639         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3640         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3641
3642         let mut as_channel_ready = None;
3643         if messages_delivered == 0 {
3644                 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3645                 as_channel_ready = Some(channel_ready);
3646                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3647                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3648                 // it before the channel_reestablish message.
3649         } else {
3650                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3651         }
3652
3653         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3654
3655         let payment_event = {
3656                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3657                 check_added_monitors!(nodes[0], 1);
3658
3659                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3660                 assert_eq!(events.len(), 1);
3661                 SendEvent::from_event(events.remove(0))
3662         };
3663         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3664
3665         if messages_delivered < 2 {
3666                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3667         } else {
3668                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3669                 if messages_delivered >= 3 {
3670                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3671                         check_added_monitors!(nodes[1], 1);
3672                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3673
3674                         if messages_delivered >= 4 {
3675                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3676                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3677                                 check_added_monitors!(nodes[0], 1);
3678
3679                                 if messages_delivered >= 5 {
3680                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3681                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3682                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3683                                         check_added_monitors!(nodes[0], 1);
3684
3685                                         if messages_delivered >= 6 {
3686                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3687                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3688                                                 check_added_monitors!(nodes[1], 1);
3689                                         }
3690                                 }
3691                         }
3692                 }
3693         }
3694
3695         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3696         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3697         if messages_delivered < 3 {
3698                 if simulate_broken_lnd {
3699                         // lnd has a long-standing bug where they send a channel_ready prior to a
3700                         // channel_reestablish if you reconnect prior to channel_ready time.
3701                         //
3702                         // Here we simulate that behavior, delivering a channel_ready immediately on
3703                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3704                         // in `reconnect_nodes` but we currently don't fail based on that.
3705                         //
3706                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3707                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3708                 }
3709                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3710                 // received on either side, both sides will need to resend them.
3711                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3712         } else if messages_delivered == 3 {
3713                 // nodes[0] still wants its RAA + commitment_signed
3714                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3715         } else if messages_delivered == 4 {
3716                 // nodes[0] still wants its commitment_signed
3717                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3718         } else if messages_delivered == 5 {
3719                 // nodes[1] still wants its final RAA
3720                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3721         } else if messages_delivered == 6 {
3722                 // Everything was delivered...
3723                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3724         }
3725
3726         let events_1 = nodes[1].node.get_and_clear_pending_events();
3727         assert_eq!(events_1.len(), 1);
3728         match events_1[0] {
3729                 Event::PendingHTLCsForwardable { .. } => { },
3730                 _ => panic!("Unexpected event"),
3731         };
3732
3733         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3734         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3735         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3736
3737         nodes[1].node.process_pending_htlc_forwards();
3738
3739         let events_2 = nodes[1].node.get_and_clear_pending_events();
3740         assert_eq!(events_2.len(), 1);
3741         match events_2[0] {
3742                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3743                         assert_eq!(payment_hash_1, *payment_hash);
3744                         assert_eq!(amount_msat, 1_000_000);
3745                         match &purpose {
3746                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3747                                         assert!(payment_preimage.is_none());
3748                                         assert_eq!(payment_secret_1, *payment_secret);
3749                                 },
3750                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3751                         }
3752                 },
3753                 _ => panic!("Unexpected event"),
3754         }
3755
3756         nodes[1].node.claim_funds(payment_preimage_1);
3757         check_added_monitors!(nodes[1], 1);
3758         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3759
3760         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3761         assert_eq!(events_3.len(), 1);
3762         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3763                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3764                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3765                         assert!(updates.update_add_htlcs.is_empty());
3766                         assert!(updates.update_fail_htlcs.is_empty());
3767                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3768                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3769                         assert!(updates.update_fee.is_none());
3770                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3771                 },
3772                 _ => panic!("Unexpected event"),
3773         };
3774
3775         if messages_delivered >= 1 {
3776                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3777
3778                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3779                 assert_eq!(events_4.len(), 1);
3780                 match events_4[0] {
3781                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3782                                 assert_eq!(payment_preimage_1, *payment_preimage);
3783                                 assert_eq!(payment_hash_1, *payment_hash);
3784                         },
3785                         _ => panic!("Unexpected event"),
3786                 }
3787
3788                 if messages_delivered >= 2 {
3789                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3790                         check_added_monitors!(nodes[0], 1);
3791                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3792
3793                         if messages_delivered >= 3 {
3794                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3795                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3796                                 check_added_monitors!(nodes[1], 1);
3797
3798                                 if messages_delivered >= 4 {
3799                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3800                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3801                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3802                                         check_added_monitors!(nodes[1], 1);
3803
3804                                         if messages_delivered >= 5 {
3805                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3806                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3807                                                 check_added_monitors!(nodes[0], 1);
3808                                         }
3809                                 }
3810                         }
3811                 }
3812         }
3813
3814         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3815         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3816         if messages_delivered < 2 {
3817                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3818                 if messages_delivered < 1 {
3819                         expect_payment_sent!(nodes[0], payment_preimage_1);
3820                 } else {
3821                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3822                 }
3823         } else if messages_delivered == 2 {
3824                 // nodes[0] still wants its RAA + commitment_signed
3825                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3826         } else if messages_delivered == 3 {
3827                 // nodes[0] still wants its commitment_signed
3828                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3829         } else if messages_delivered == 4 {
3830                 // nodes[1] still wants its final RAA
3831                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3832         } else if messages_delivered == 5 {
3833                 // Everything was delivered...
3834                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3835         }
3836
3837         if messages_delivered == 1 || messages_delivered == 2 {
3838                 expect_payment_path_successful!(nodes[0]);
3839         }
3840
3841         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3842         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3843         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3844
3845         if messages_delivered > 2 {
3846                 expect_payment_path_successful!(nodes[0]);
3847         }
3848
3849         // Channel should still work fine...
3850         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3851         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3852         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3853 }
3854
3855 #[test]
3856 fn test_drop_messages_peer_disconnect_a() {
3857         do_test_drop_messages_peer_disconnect(0, true);
3858         do_test_drop_messages_peer_disconnect(0, false);
3859         do_test_drop_messages_peer_disconnect(1, false);
3860         do_test_drop_messages_peer_disconnect(2, false);
3861 }
3862
3863 #[test]
3864 fn test_drop_messages_peer_disconnect_b() {
3865         do_test_drop_messages_peer_disconnect(3, false);
3866         do_test_drop_messages_peer_disconnect(4, false);
3867         do_test_drop_messages_peer_disconnect(5, false);
3868         do_test_drop_messages_peer_disconnect(6, false);
3869 }
3870
3871 #[test]
3872 fn test_funding_peer_disconnect() {
3873         // Test that we can lock in our funding tx while disconnected
3874         let chanmon_cfgs = create_chanmon_cfgs(2);
3875         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3876         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3877         let persister: test_utils::TestPersister;
3878         let new_chain_monitor: test_utils::TestChainMonitor;
3879         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3880         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3881         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3882
3883         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3884         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3885
3886         confirm_transaction(&nodes[0], &tx);
3887         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3888         assert!(events_1.is_empty());
3889
3890         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3891
3892         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3893         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3894
3895         confirm_transaction(&nodes[1], &tx);
3896         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3897         assert!(events_2.is_empty());
3898
3899         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3900         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3901         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3902         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3903
3904         // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3905         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3906         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3907         assert_eq!(events_3.len(), 1);
3908         let as_channel_ready = match events_3[0] {
3909                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3910                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3911                         msg.clone()
3912                 },
3913                 _ => panic!("Unexpected event {:?}", events_3[0]),
3914         };
3915
3916         // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3917         // announcement_signatures as well as channel_update.
3918         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3919         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3920         assert_eq!(events_4.len(), 3);
3921         let chan_id;
3922         let bs_channel_ready = match events_4[0] {
3923                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3924                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3925                         chan_id = msg.channel_id;
3926                         msg.clone()
3927                 },
3928                 _ => panic!("Unexpected event {:?}", events_4[0]),
3929         };
3930         let bs_announcement_sigs = match events_4[1] {
3931                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3932                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3933                         msg.clone()
3934                 },
3935                 _ => panic!("Unexpected event {:?}", events_4[1]),
3936         };
3937         match events_4[2] {
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_4[2]),
3942         }
3943
3944         // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3945         // generates a duplicative private channel_update
3946         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3947         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3948         assert_eq!(events_5.len(), 1);
3949         match events_5[0] {
3950                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3951                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3952                 },
3953                 _ => panic!("Unexpected event {:?}", events_5[0]),
3954         };
3955
3956         // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3957         // announcement_signatures.
3958         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3959         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3960         assert_eq!(events_6.len(), 1);
3961         let as_announcement_sigs = match events_6[0] {
3962                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3963                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3964                         msg.clone()
3965                 },
3966                 _ => panic!("Unexpected event {:?}", events_6[0]),
3967         };
3968
3969         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3970         // broadcast the channel announcement globally, as well as re-send its (now-public)
3971         // channel_update.
3972         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3973         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3974         assert_eq!(events_7.len(), 1);
3975         let (chan_announcement, as_update) = match events_7[0] {
3976                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3977                         (msg.clone(), update_msg.clone())
3978                 },
3979                 _ => panic!("Unexpected event {:?}", events_7[0]),
3980         };
3981
3982         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3983         // same channel_announcement.
3984         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3985         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3986         assert_eq!(events_8.len(), 1);
3987         let bs_update = match events_8[0] {
3988                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3989                         assert_eq!(*msg, chan_announcement);
3990                         update_msg.clone()
3991                 },
3992                 _ => panic!("Unexpected event {:?}", events_8[0]),
3993         };
3994
3995         // Provide the channel announcement and public updates to the network graph
3996         nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3997         nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
3998         nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
3999
4000         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4001         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4002         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
4003
4004         // Check that after deserialization and reconnection we can still generate an identical
4005         // channel_announcement from the cached signatures.
4006         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4007
4008         let nodes_0_serialized = nodes[0].node.encode();
4009         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4010         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4011
4012         persister = test_utils::TestPersister::new();
4013         let keys_manager = &chanmon_cfgs[0].keys_manager;
4014         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);
4015         nodes[0].chain_monitor = &new_chain_monitor;
4016         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4017         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4018                 &mut chan_0_monitor_read, keys_manager).unwrap();
4019         assert!(chan_0_monitor_read.is_empty());
4020
4021         let mut nodes_0_read = &nodes_0_serialized[..];
4022         let (_, nodes_0_deserialized_tmp) = {
4023                 let mut channel_monitors = HashMap::new();
4024                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4025                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4026                         default_config: UserConfig::default(),
4027                         keys_manager,
4028                         fee_estimator: node_cfgs[0].fee_estimator,
4029                         chain_monitor: nodes[0].chain_monitor,
4030                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4031                         logger: nodes[0].logger,
4032                         channel_monitors,
4033                 }).unwrap()
4034         };
4035         nodes_0_deserialized = nodes_0_deserialized_tmp;
4036         assert!(nodes_0_read.is_empty());
4037
4038         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4039         nodes[0].node = &nodes_0_deserialized;
4040         check_added_monitors!(nodes[0], 1);
4041
4042         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4043
4044         // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4045         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4046         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4047         let mut found_announcement = false;
4048         for event in msgs.iter() {
4049                 match event {
4050                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4051                                 if *msg == chan_announcement { found_announcement = true; }
4052                         },
4053                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4054                         _ => panic!("Unexpected event"),
4055                 }
4056         }
4057         assert!(found_announcement);
4058 }
4059
4060 #[test]
4061 fn test_channel_ready_without_best_block_updated() {
4062         // Previously, if we were offline when a funding transaction was locked in, and then we came
4063         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4064         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4065         // channel_ready immediately instead.
4066         let chanmon_cfgs = create_chanmon_cfgs(2);
4067         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4068         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4069         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4070         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4071
4072         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4073
4074         let conf_height = nodes[0].best_block_info().1 + 1;
4075         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4076         let block_txn = [funding_tx];
4077         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4078         let conf_block_header = nodes[0].get_block_header(conf_height);
4079         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4080
4081         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4082         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4083         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4084 }
4085
4086 #[test]
4087 fn test_drop_messages_peer_disconnect_dual_htlc() {
4088         // Test that we can handle reconnecting when both sides of a channel have pending
4089         // commitment_updates when we disconnect.
4090         let chanmon_cfgs = create_chanmon_cfgs(2);
4091         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4092         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4093         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4094         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4095
4096         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4097
4098         // Now try to send a second payment which will fail to send
4099         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4100         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4101         check_added_monitors!(nodes[0], 1);
4102
4103         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4104         assert_eq!(events_1.len(), 1);
4105         match events_1[0] {
4106                 MessageSendEvent::UpdateHTLCs { .. } => {},
4107                 _ => panic!("Unexpected event"),
4108         }
4109
4110         nodes[1].node.claim_funds(payment_preimage_1);
4111         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4112         check_added_monitors!(nodes[1], 1);
4113
4114         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4115         assert_eq!(events_2.len(), 1);
4116         match events_2[0] {
4117                 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 } } => {
4118                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4119                         assert!(update_add_htlcs.is_empty());
4120                         assert_eq!(update_fulfill_htlcs.len(), 1);
4121                         assert!(update_fail_htlcs.is_empty());
4122                         assert!(update_fail_malformed_htlcs.is_empty());
4123                         assert!(update_fee.is_none());
4124
4125                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4126                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4127                         assert_eq!(events_3.len(), 1);
4128                         match events_3[0] {
4129                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4130                                         assert_eq!(*payment_preimage, payment_preimage_1);
4131                                         assert_eq!(*payment_hash, payment_hash_1);
4132                                 },
4133                                 _ => panic!("Unexpected event"),
4134                         }
4135
4136                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4137                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4138                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4139                         check_added_monitors!(nodes[0], 1);
4140                 },
4141                 _ => panic!("Unexpected event"),
4142         }
4143
4144         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4145         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4146
4147         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4148         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4149         assert_eq!(reestablish_1.len(), 1);
4150         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4151         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4152         assert_eq!(reestablish_2.len(), 1);
4153
4154         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4155         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4156         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4157         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4158
4159         assert!(as_resp.0.is_none());
4160         assert!(bs_resp.0.is_none());
4161
4162         assert!(bs_resp.1.is_none());
4163         assert!(bs_resp.2.is_none());
4164
4165         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4166
4167         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4168         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4169         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4170         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4171         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4172         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4173         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4174         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4175         // No commitment_signed so get_event_msg's assert(len == 1) passes
4176         check_added_monitors!(nodes[1], 1);
4177
4178         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4179         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4180         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4181         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4182         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4183         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4184         assert!(bs_second_commitment_signed.update_fee.is_none());
4185         check_added_monitors!(nodes[1], 1);
4186
4187         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4188         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4189         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4190         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4191         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4192         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4193         assert!(as_commitment_signed.update_fee.is_none());
4194         check_added_monitors!(nodes[0], 1);
4195
4196         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4197         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4198         // No commitment_signed so get_event_msg's assert(len == 1) passes
4199         check_added_monitors!(nodes[0], 1);
4200
4201         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4202         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4203         // No commitment_signed so get_event_msg's assert(len == 1) passes
4204         check_added_monitors!(nodes[1], 1);
4205
4206         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4207         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4208         check_added_monitors!(nodes[1], 1);
4209
4210         expect_pending_htlcs_forwardable!(nodes[1]);
4211
4212         let events_5 = nodes[1].node.get_and_clear_pending_events();
4213         assert_eq!(events_5.len(), 1);
4214         match events_5[0] {
4215                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4216                         assert_eq!(payment_hash_2, *payment_hash);
4217                         match &purpose {
4218                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4219                                         assert!(payment_preimage.is_none());
4220                                         assert_eq!(payment_secret_2, *payment_secret);
4221                                 },
4222                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4223                         }
4224                 },
4225                 _ => panic!("Unexpected event"),
4226         }
4227
4228         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4229         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4230         check_added_monitors!(nodes[0], 1);
4231
4232         expect_payment_path_successful!(nodes[0]);
4233         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4234 }
4235
4236 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4237         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4238         // to avoid our counterparty failing the channel.
4239         let chanmon_cfgs = create_chanmon_cfgs(2);
4240         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4241         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4242         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4243
4244         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4245
4246         let our_payment_hash = if send_partial_mpp {
4247                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4248                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4249                 // indicates there are more HTLCs coming.
4250                 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.
4251                 let payment_id = PaymentId([42; 32]);
4252                 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();
4253                 check_added_monitors!(nodes[0], 1);
4254                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4255                 assert_eq!(events.len(), 1);
4256                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4257                 // hop should *not* yet generate any PaymentReceived event(s).
4258                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4259                 our_payment_hash
4260         } else {
4261                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4262         };
4263
4264         let mut block = Block {
4265                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4266                 txdata: vec![],
4267         };
4268         connect_block(&nodes[0], &block);
4269         connect_block(&nodes[1], &block);
4270         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4271         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4272                 block.header.prev_blockhash = block.block_hash();
4273                 connect_block(&nodes[0], &block);
4274                 connect_block(&nodes[1], &block);
4275         }
4276
4277         expect_pending_htlcs_forwardable!(nodes[1]);
4278
4279         check_added_monitors!(nodes[1], 1);
4280         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4281         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4282         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4283         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4284         assert!(htlc_timeout_updates.update_fee.is_none());
4285
4286         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4287         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4288         // 100_000 msat as u64, followed by the height at which we failed back above
4289         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4290         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4291         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4292 }
4293
4294 #[test]
4295 fn test_htlc_timeout() {
4296         do_test_htlc_timeout(true);
4297         do_test_htlc_timeout(false);
4298 }
4299
4300 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4301         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4302         let chanmon_cfgs = create_chanmon_cfgs(3);
4303         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4304         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4305         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4306         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4307         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4308
4309         // Make sure all nodes are at the same starting height
4310         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4311         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4312         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4313
4314         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4315         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4316         {
4317                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4318         }
4319         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4320         check_added_monitors!(nodes[1], 1);
4321
4322         // Now attempt to route a second payment, which should be placed in the holding cell
4323         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4324         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4325         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4326         if forwarded_htlc {
4327                 check_added_monitors!(nodes[0], 1);
4328                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4329                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4330                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4331                 expect_pending_htlcs_forwardable!(nodes[1]);
4332         }
4333         check_added_monitors!(nodes[1], 0);
4334
4335         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4336         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4337         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4338         connect_blocks(&nodes[1], 1);
4339
4340         if forwarded_htlc {
4341                 expect_pending_htlcs_forwardable!(nodes[1]);
4342                 check_added_monitors!(nodes[1], 1);
4343                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4344                 assert_eq!(fail_commit.len(), 1);
4345                 match fail_commit[0] {
4346                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4347                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4348                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4349                         },
4350                         _ => unreachable!(),
4351                 }
4352                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4353         } else {
4354                 let events = nodes[1].node.get_and_clear_pending_events();
4355                 assert_eq!(events.len(), 2);
4356                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4357                         assert_eq!(*payment_hash, second_payment_hash);
4358                 } else { panic!("Unexpected event"); }
4359                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4360                         assert_eq!(*payment_hash, second_payment_hash);
4361                 } else { panic!("Unexpected event"); }
4362         }
4363 }
4364
4365 #[test]
4366 fn test_holding_cell_htlc_add_timeouts() {
4367         do_test_holding_cell_htlc_add_timeouts(false);
4368         do_test_holding_cell_htlc_add_timeouts(true);
4369 }
4370
4371 #[test]
4372 fn test_no_txn_manager_serialize_deserialize() {
4373         let chanmon_cfgs = create_chanmon_cfgs(2);
4374         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4375         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4376         let logger: test_utils::TestLogger;
4377         let fee_estimator: test_utils::TestFeeEstimator;
4378         let persister: test_utils::TestPersister;
4379         let new_chain_monitor: test_utils::TestChainMonitor;
4380         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4381         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4382
4383         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4384
4385         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4386
4387         let nodes_0_serialized = nodes[0].node.encode();
4388         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4389         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4390                 .write(&mut chan_0_monitor_serialized).unwrap();
4391
4392         logger = test_utils::TestLogger::new();
4393         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4394         persister = test_utils::TestPersister::new();
4395         let keys_manager = &chanmon_cfgs[0].keys_manager;
4396         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4397         nodes[0].chain_monitor = &new_chain_monitor;
4398         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4399         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4400                 &mut chan_0_monitor_read, keys_manager).unwrap();
4401         assert!(chan_0_monitor_read.is_empty());
4402
4403         let mut nodes_0_read = &nodes_0_serialized[..];
4404         let config = UserConfig::default();
4405         let (_, nodes_0_deserialized_tmp) = {
4406                 let mut channel_monitors = HashMap::new();
4407                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4408                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4409                         default_config: config,
4410                         keys_manager,
4411                         fee_estimator: &fee_estimator,
4412                         chain_monitor: nodes[0].chain_monitor,
4413                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4414                         logger: &logger,
4415                         channel_monitors,
4416                 }).unwrap()
4417         };
4418         nodes_0_deserialized = nodes_0_deserialized_tmp;
4419         assert!(nodes_0_read.is_empty());
4420
4421         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4422         nodes[0].node = &nodes_0_deserialized;
4423         assert_eq!(nodes[0].node.list_channels().len(), 1);
4424         check_added_monitors!(nodes[0], 1);
4425
4426         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4427         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4428         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4429         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4430
4431         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4432         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4433         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4434         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4435
4436         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4437         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4438         for node in nodes.iter() {
4439                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4440                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4441                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4442         }
4443
4444         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4445 }
4446
4447 #[test]
4448 fn test_manager_serialize_deserialize_events() {
4449         // This test makes sure the events field in ChannelManager survives de/serialization
4450         let chanmon_cfgs = create_chanmon_cfgs(2);
4451         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4452         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4453         let fee_estimator: test_utils::TestFeeEstimator;
4454         let persister: test_utils::TestPersister;
4455         let logger: test_utils::TestLogger;
4456         let new_chain_monitor: test_utils::TestChainMonitor;
4457         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4458         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4459
4460         // Start creating a channel, but stop right before broadcasting the funding transaction
4461         let channel_value = 100000;
4462         let push_msat = 10001;
4463         let a_flags = InitFeatures::known();
4464         let b_flags = InitFeatures::known();
4465         let node_a = nodes.remove(0);
4466         let node_b = nodes.remove(0);
4467         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4468         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()));
4469         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()));
4470
4471         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4472
4473         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4474         check_added_monitors!(node_a, 0);
4475
4476         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()));
4477         {
4478                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4479                 assert_eq!(added_monitors.len(), 1);
4480                 assert_eq!(added_monitors[0].0, funding_output);
4481                 added_monitors.clear();
4482         }
4483
4484         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4485         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4486         {
4487                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4488                 assert_eq!(added_monitors.len(), 1);
4489                 assert_eq!(added_monitors[0].0, funding_output);
4490                 added_monitors.clear();
4491         }
4492         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4493
4494         nodes.push(node_a);
4495         nodes.push(node_b);
4496
4497         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4498         let nodes_0_serialized = nodes[0].node.encode();
4499         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4500         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4501
4502         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4503         logger = test_utils::TestLogger::new();
4504         persister = test_utils::TestPersister::new();
4505         let keys_manager = &chanmon_cfgs[0].keys_manager;
4506         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4507         nodes[0].chain_monitor = &new_chain_monitor;
4508         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4509         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4510                 &mut chan_0_monitor_read, keys_manager).unwrap();
4511         assert!(chan_0_monitor_read.is_empty());
4512
4513         let mut nodes_0_read = &nodes_0_serialized[..];
4514         let config = UserConfig::default();
4515         let (_, nodes_0_deserialized_tmp) = {
4516                 let mut channel_monitors = HashMap::new();
4517                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4518                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4519                         default_config: config,
4520                         keys_manager,
4521                         fee_estimator: &fee_estimator,
4522                         chain_monitor: nodes[0].chain_monitor,
4523                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4524                         logger: &logger,
4525                         channel_monitors,
4526                 }).unwrap()
4527         };
4528         nodes_0_deserialized = nodes_0_deserialized_tmp;
4529         assert!(nodes_0_read.is_empty());
4530
4531         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4532
4533         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4534         nodes[0].node = &nodes_0_deserialized;
4535
4536         // After deserializing, make sure the funding_transaction is still held by the channel manager
4537         let events_4 = nodes[0].node.get_and_clear_pending_events();
4538         assert_eq!(events_4.len(), 0);
4539         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4540         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4541
4542         // Make sure the channel is functioning as though the de/serialization never happened
4543         assert_eq!(nodes[0].node.list_channels().len(), 1);
4544         check_added_monitors!(nodes[0], 1);
4545
4546         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4547         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4548         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4549         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4550
4551         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4552         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4553         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4554         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4555
4556         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4557         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4558         for node in nodes.iter() {
4559                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4560                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4561                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4562         }
4563
4564         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4565 }
4566
4567 #[test]
4568 fn test_simple_manager_serialize_deserialize() {
4569         let chanmon_cfgs = create_chanmon_cfgs(2);
4570         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4571         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4572         let logger: test_utils::TestLogger;
4573         let fee_estimator: test_utils::TestFeeEstimator;
4574         let persister: test_utils::TestPersister;
4575         let new_chain_monitor: test_utils::TestChainMonitor;
4576         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4577         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4578         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4579
4580         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4581         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4582
4583         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4584
4585         let nodes_0_serialized = nodes[0].node.encode();
4586         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4587         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4588
4589         logger = test_utils::TestLogger::new();
4590         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4591         persister = test_utils::TestPersister::new();
4592         let keys_manager = &chanmon_cfgs[0].keys_manager;
4593         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4594         nodes[0].chain_monitor = &new_chain_monitor;
4595         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4596         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4597                 &mut chan_0_monitor_read, keys_manager).unwrap();
4598         assert!(chan_0_monitor_read.is_empty());
4599
4600         let mut nodes_0_read = &nodes_0_serialized[..];
4601         let (_, nodes_0_deserialized_tmp) = {
4602                 let mut channel_monitors = HashMap::new();
4603                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4604                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4605                         default_config: UserConfig::default(),
4606                         keys_manager,
4607                         fee_estimator: &fee_estimator,
4608                         chain_monitor: nodes[0].chain_monitor,
4609                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4610                         logger: &logger,
4611                         channel_monitors,
4612                 }).unwrap()
4613         };
4614         nodes_0_deserialized = nodes_0_deserialized_tmp;
4615         assert!(nodes_0_read.is_empty());
4616
4617         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4618         nodes[0].node = &nodes_0_deserialized;
4619         check_added_monitors!(nodes[0], 1);
4620
4621         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4622
4623         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4624         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4625 }
4626
4627 #[test]
4628 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4629         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4630         let chanmon_cfgs = create_chanmon_cfgs(4);
4631         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4632         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4633         let logger: test_utils::TestLogger;
4634         let fee_estimator: test_utils::TestFeeEstimator;
4635         let persister: test_utils::TestPersister;
4636         let new_chain_monitor: test_utils::TestChainMonitor;
4637         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4638         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4639         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4640         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4641         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4642
4643         let mut node_0_stale_monitors_serialized = Vec::new();
4644         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4645                 let mut writer = test_utils::TestVecWriter(Vec::new());
4646                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4647                 node_0_stale_monitors_serialized.push(writer.0);
4648         }
4649
4650         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4651
4652         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4653         let nodes_0_serialized = nodes[0].node.encode();
4654
4655         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4656         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4657         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4658         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4659
4660         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4661         // nodes[3])
4662         let mut node_0_monitors_serialized = Vec::new();
4663         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4664                 let mut writer = test_utils::TestVecWriter(Vec::new());
4665                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4666                 node_0_monitors_serialized.push(writer.0);
4667         }
4668
4669         logger = test_utils::TestLogger::new();
4670         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4671         persister = test_utils::TestPersister::new();
4672         let keys_manager = &chanmon_cfgs[0].keys_manager;
4673         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4674         nodes[0].chain_monitor = &new_chain_monitor;
4675
4676
4677         let mut node_0_stale_monitors = Vec::new();
4678         for serialized in node_0_stale_monitors_serialized.iter() {
4679                 let mut read = &serialized[..];
4680                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4681                 assert!(read.is_empty());
4682                 node_0_stale_monitors.push(monitor);
4683         }
4684
4685         let mut node_0_monitors = Vec::new();
4686         for serialized in node_0_monitors_serialized.iter() {
4687                 let mut read = &serialized[..];
4688                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4689                 assert!(read.is_empty());
4690                 node_0_monitors.push(monitor);
4691         }
4692
4693         let mut nodes_0_read = &nodes_0_serialized[..];
4694         if let Err(msgs::DecodeError::InvalidValue) =
4695                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4696                 default_config: UserConfig::default(),
4697                 keys_manager,
4698                 fee_estimator: &fee_estimator,
4699                 chain_monitor: nodes[0].chain_monitor,
4700                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4701                 logger: &logger,
4702                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4703         }) { } else {
4704                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4705         };
4706
4707         let mut nodes_0_read = &nodes_0_serialized[..];
4708         let (_, nodes_0_deserialized_tmp) =
4709                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4710                 default_config: UserConfig::default(),
4711                 keys_manager,
4712                 fee_estimator: &fee_estimator,
4713                 chain_monitor: nodes[0].chain_monitor,
4714                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4715                 logger: &logger,
4716                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4717         }).unwrap();
4718         nodes_0_deserialized = nodes_0_deserialized_tmp;
4719         assert!(nodes_0_read.is_empty());
4720
4721         { // Channel close should result in a commitment tx
4722                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4723                 assert_eq!(txn.len(), 1);
4724                 check_spends!(txn[0], funding_tx);
4725                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4726         }
4727
4728         for monitor in node_0_monitors.drain(..) {
4729                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4730                 check_added_monitors!(nodes[0], 1);
4731         }
4732         nodes[0].node = &nodes_0_deserialized;
4733         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4734
4735         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4736         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4737         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4738         //... and we can even still claim the payment!
4739         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4740
4741         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4742         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4743         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4744         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4745         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4746         assert_eq!(msg_events.len(), 1);
4747         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4748                 match action {
4749                         &ErrorAction::SendErrorMessage { ref msg } => {
4750                                 assert_eq!(msg.channel_id, channel_id);
4751                         },
4752                         _ => panic!("Unexpected event!"),
4753                 }
4754         }
4755 }
4756
4757 macro_rules! check_spendable_outputs {
4758         ($node: expr, $keysinterface: expr) => {
4759                 {
4760                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4761                         let mut txn = Vec::new();
4762                         let mut all_outputs = Vec::new();
4763                         let secp_ctx = Secp256k1::new();
4764                         for event in events.drain(..) {
4765                                 match event {
4766                                         Event::SpendableOutputs { mut outputs } => {
4767                                                 for outp in outputs.drain(..) {
4768                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4769                                                         all_outputs.push(outp);
4770                                                 }
4771                                         },
4772                                         _ => panic!("Unexpected event"),
4773                                 };
4774                         }
4775                         if all_outputs.len() > 1 {
4776                                 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) {
4777                                         txn.push(tx);
4778                                 }
4779                         }
4780                         txn
4781                 }
4782         }
4783 }
4784
4785 #[test]
4786 fn test_claim_sizeable_push_msat() {
4787         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4788         let chanmon_cfgs = create_chanmon_cfgs(2);
4789         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4790         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4791         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4792
4793         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4794         nodes[1].node.force_close_channel(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4795         check_closed_broadcast!(nodes[1], true);
4796         check_added_monitors!(nodes[1], 1);
4797         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4798         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4799         assert_eq!(node_txn.len(), 1);
4800         check_spends!(node_txn[0], chan.3);
4801         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
4802
4803         mine_transaction(&nodes[1], &node_txn[0]);
4804         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4805
4806         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4807         assert_eq!(spend_txn.len(), 1);
4808         assert_eq!(spend_txn[0].input.len(), 1);
4809         check_spends!(spend_txn[0], node_txn[0]);
4810         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4811 }
4812
4813 #[test]
4814 fn test_claim_on_remote_sizeable_push_msat() {
4815         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4816         // to_remote output is encumbered by a P2WPKH
4817         let chanmon_cfgs = create_chanmon_cfgs(2);
4818         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4819         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4820         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4821
4822         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4823         nodes[0].node.force_close_channel(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4824         check_closed_broadcast!(nodes[0], true);
4825         check_added_monitors!(nodes[0], 1);
4826         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4827
4828         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4829         assert_eq!(node_txn.len(), 1);
4830         check_spends!(node_txn[0], chan.3);
4831         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
4832
4833         mine_transaction(&nodes[1], &node_txn[0]);
4834         check_closed_broadcast!(nodes[1], true);
4835         check_added_monitors!(nodes[1], 1);
4836         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4837         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4838
4839         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4840         assert_eq!(spend_txn.len(), 1);
4841         check_spends!(spend_txn[0], node_txn[0]);
4842 }
4843
4844 #[test]
4845 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4846         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4847         // to_remote output is encumbered by a P2WPKH
4848
4849         let chanmon_cfgs = create_chanmon_cfgs(2);
4850         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4851         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4852         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4853
4854         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4855         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4856         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4857         assert_eq!(revoked_local_txn[0].input.len(), 1);
4858         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4859
4860         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4861         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4862         check_closed_broadcast!(nodes[1], true);
4863         check_added_monitors!(nodes[1], 1);
4864         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4865
4866         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4867         mine_transaction(&nodes[1], &node_txn[0]);
4868         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4869
4870         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4871         assert_eq!(spend_txn.len(), 3);
4872         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4873         check_spends!(spend_txn[1], node_txn[0]);
4874         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4875 }
4876
4877 #[test]
4878 fn test_static_spendable_outputs_preimage_tx() {
4879         let chanmon_cfgs = create_chanmon_cfgs(2);
4880         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4881         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4882         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4883
4884         // Create some initial channels
4885         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4886
4887         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4888
4889         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4890         assert_eq!(commitment_tx[0].input.len(), 1);
4891         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4892
4893         // Settle A's commitment tx on B's chain
4894         nodes[1].node.claim_funds(payment_preimage);
4895         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4896         check_added_monitors!(nodes[1], 1);
4897         mine_transaction(&nodes[1], &commitment_tx[0]);
4898         check_added_monitors!(nodes[1], 1);
4899         let events = nodes[1].node.get_and_clear_pending_msg_events();
4900         match events[0] {
4901                 MessageSendEvent::UpdateHTLCs { .. } => {},
4902                 _ => panic!("Unexpected event"),
4903         }
4904         match events[1] {
4905                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4906                 _ => panic!("Unexepected event"),
4907         }
4908
4909         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4910         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4911         assert_eq!(node_txn.len(), 3);
4912         check_spends!(node_txn[0], commitment_tx[0]);
4913         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4914         check_spends!(node_txn[1], chan_1.3);
4915         check_spends!(node_txn[2], node_txn[1]);
4916
4917         mine_transaction(&nodes[1], &node_txn[0]);
4918         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4919         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4920
4921         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4922         assert_eq!(spend_txn.len(), 1);
4923         check_spends!(spend_txn[0], node_txn[0]);
4924 }
4925
4926 #[test]
4927 fn test_static_spendable_outputs_timeout_tx() {
4928         let chanmon_cfgs = create_chanmon_cfgs(2);
4929         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4930         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4931         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4932
4933         // Create some initial channels
4934         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4935
4936         // Rebalance the network a bit by relaying one payment through all the channels ...
4937         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4938
4939         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4940
4941         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4942         assert_eq!(commitment_tx[0].input.len(), 1);
4943         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4944
4945         // Settle A's commitment tx on B' chain
4946         mine_transaction(&nodes[1], &commitment_tx[0]);
4947         check_added_monitors!(nodes[1], 1);
4948         let events = nodes[1].node.get_and_clear_pending_msg_events();
4949         match events[0] {
4950                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4951                 _ => panic!("Unexpected event"),
4952         }
4953         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4954
4955         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4956         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4957         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4958         check_spends!(node_txn[0], chan_1.3.clone());
4959         check_spends!(node_txn[1],  commitment_tx[0].clone());
4960         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4961
4962         mine_transaction(&nodes[1], &node_txn[1]);
4963         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4964         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4965         expect_payment_failed!(nodes[1], our_payment_hash, true);
4966
4967         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4968         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4969         check_spends!(spend_txn[0], commitment_tx[0]);
4970         check_spends!(spend_txn[1], node_txn[1]);
4971         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4972 }
4973
4974 #[test]
4975 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4976         let chanmon_cfgs = create_chanmon_cfgs(2);
4977         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4978         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4979         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4980
4981         // Create some initial channels
4982         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4983
4984         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4985         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4986         assert_eq!(revoked_local_txn[0].input.len(), 1);
4987         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4988
4989         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4990
4991         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4992         check_closed_broadcast!(nodes[1], true);
4993         check_added_monitors!(nodes[1], 1);
4994         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4995
4996         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4997         assert_eq!(node_txn.len(), 2);
4998         assert_eq!(node_txn[0].input.len(), 2);
4999         check_spends!(node_txn[0], revoked_local_txn[0]);
5000
5001         mine_transaction(&nodes[1], &node_txn[0]);
5002         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5003
5004         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5005         assert_eq!(spend_txn.len(), 1);
5006         check_spends!(spend_txn[0], node_txn[0]);
5007 }
5008
5009 #[test]
5010 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5011         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5012         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5013         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5014         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5015         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5016
5017         // Create some initial channels
5018         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5019
5020         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5021         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5022         assert_eq!(revoked_local_txn[0].input.len(), 1);
5023         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5024
5025         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5026
5027         // A will generate HTLC-Timeout from revoked commitment tx
5028         mine_transaction(&nodes[0], &revoked_local_txn[0]);
5029         check_closed_broadcast!(nodes[0], true);
5030         check_added_monitors!(nodes[0], 1);
5031         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5032         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5033
5034         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5035         assert_eq!(revoked_htlc_txn.len(), 2);
5036         check_spends!(revoked_htlc_txn[0], chan_1.3);
5037         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5038         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5039         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5040         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5041
5042         // B will generate justice tx from A's revoked commitment/HTLC tx
5043         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5044         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5045         check_closed_broadcast!(nodes[1], true);
5046         check_added_monitors!(nodes[1], 1);
5047         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5048
5049         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5050         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5051         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5052         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5053         // transactions next...
5054         assert_eq!(node_txn[0].input.len(), 3);
5055         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5056
5057         assert_eq!(node_txn[1].input.len(), 2);
5058         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5059         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5060                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5061         } else {
5062                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5063                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5064         }
5065
5066         assert_eq!(node_txn[2].input.len(), 1);
5067         check_spends!(node_txn[2], chan_1.3);
5068
5069         mine_transaction(&nodes[1], &node_txn[1]);
5070         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5071
5072         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5073         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5074         assert_eq!(spend_txn.len(), 1);
5075         assert_eq!(spend_txn[0].input.len(), 1);
5076         check_spends!(spend_txn[0], node_txn[1]);
5077 }
5078
5079 #[test]
5080 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5081         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5082         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5083         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5084         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5085         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5086
5087         // Create some initial channels
5088         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5089
5090         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5091         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5092         assert_eq!(revoked_local_txn[0].input.len(), 1);
5093         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5094
5095         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5096         assert_eq!(revoked_local_txn[0].output.len(), 2);
5097
5098         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5099
5100         // B will generate HTLC-Success from revoked commitment tx
5101         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5102         check_closed_broadcast!(nodes[1], true);
5103         check_added_monitors!(nodes[1], 1);
5104         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5105         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5106
5107         assert_eq!(revoked_htlc_txn.len(), 2);
5108         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5109         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5110         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5111
5112         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5113         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5114         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5115
5116         // A will generate justice tx from B's revoked commitment/HTLC tx
5117         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5118         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5119         check_closed_broadcast!(nodes[0], true);
5120         check_added_monitors!(nodes[0], 1);
5121         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5122
5123         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5124         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5125
5126         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5127         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5128         // transactions next...
5129         assert_eq!(node_txn[0].input.len(), 2);
5130         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5131         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5132                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5133         } else {
5134                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5135                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5136         }
5137
5138         assert_eq!(node_txn[1].input.len(), 1);
5139         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5140
5141         check_spends!(node_txn[2], chan_1.3);
5142
5143         mine_transaction(&nodes[0], &node_txn[1]);
5144         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5145
5146         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5147         // didn't try to generate any new transactions.
5148
5149         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5150         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5151         assert_eq!(spend_txn.len(), 3);
5152         assert_eq!(spend_txn[0].input.len(), 1);
5153         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5154         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5155         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5156         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5157 }
5158
5159 #[test]
5160 fn test_onchain_to_onchain_claim() {
5161         // Test that in case of channel closure, we detect the state of output and claim HTLC
5162         // on downstream peer's remote commitment tx.
5163         // First, have C claim an HTLC against its own latest commitment transaction.
5164         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5165         // channel.
5166         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5167         // gets broadcast.
5168
5169         let chanmon_cfgs = create_chanmon_cfgs(3);
5170         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5171         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5172         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5173
5174         // Create some initial channels
5175         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5176         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5177
5178         // Ensure all nodes are at the same height
5179         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5180         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5181         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5182         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5183
5184         // Rebalance the network a bit by relaying one payment through all the channels ...
5185         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5186         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5187
5188         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5189         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5190         check_spends!(commitment_tx[0], chan_2.3);
5191         nodes[2].node.claim_funds(payment_preimage);
5192         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5193         check_added_monitors!(nodes[2], 1);
5194         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5195         assert!(updates.update_add_htlcs.is_empty());
5196         assert!(updates.update_fail_htlcs.is_empty());
5197         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5198         assert!(updates.update_fail_malformed_htlcs.is_empty());
5199
5200         mine_transaction(&nodes[2], &commitment_tx[0]);
5201         check_closed_broadcast!(nodes[2], true);
5202         check_added_monitors!(nodes[2], 1);
5203         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5204
5205         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5206         assert_eq!(c_txn.len(), 3);
5207         assert_eq!(c_txn[0], c_txn[2]);
5208         assert_eq!(commitment_tx[0], c_txn[1]);
5209         check_spends!(c_txn[1], chan_2.3);
5210         check_spends!(c_txn[2], c_txn[1]);
5211         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5212         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5213         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5214         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5215
5216         // 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
5217         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5218         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5219         check_added_monitors!(nodes[1], 1);
5220         let events = nodes[1].node.get_and_clear_pending_events();
5221         assert_eq!(events.len(), 2);
5222         match events[0] {
5223                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5224                 _ => panic!("Unexpected event"),
5225         }
5226         match events[1] {
5227                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5228                         assert_eq!(fee_earned_msat, Some(1000));
5229                         assert_eq!(prev_channel_id, Some(chan_1.2));
5230                         assert_eq!(claim_from_onchain_tx, true);
5231                         assert_eq!(next_channel_id, Some(chan_2.2));
5232                 },
5233                 _ => panic!("Unexpected event"),
5234         }
5235         {
5236                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5237                 // ChannelMonitor: claim tx
5238                 assert_eq!(b_txn.len(), 1);
5239                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5240                 b_txn.clear();
5241         }
5242         check_added_monitors!(nodes[1], 1);
5243         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5244         assert_eq!(msg_events.len(), 3);
5245         match msg_events[0] {
5246                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5247                 _ => panic!("Unexpected event"),
5248         }
5249         match msg_events[1] {
5250                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5251                 _ => panic!("Unexpected event"),
5252         }
5253         match msg_events[2] {
5254                 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, .. } } => {
5255                         assert!(update_add_htlcs.is_empty());
5256                         assert!(update_fail_htlcs.is_empty());
5257                         assert_eq!(update_fulfill_htlcs.len(), 1);
5258                         assert!(update_fail_malformed_htlcs.is_empty());
5259                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5260                 },
5261                 _ => panic!("Unexpected event"),
5262         };
5263         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5264         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5265         mine_transaction(&nodes[1], &commitment_tx[0]);
5266         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5267         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5268         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5269         assert_eq!(b_txn.len(), 3);
5270         check_spends!(b_txn[1], chan_1.3);
5271         check_spends!(b_txn[2], b_txn[1]);
5272         check_spends!(b_txn[0], commitment_tx[0]);
5273         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5274         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5275         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5276
5277         check_closed_broadcast!(nodes[1], true);
5278         check_added_monitors!(nodes[1], 1);
5279 }
5280
5281 #[test]
5282 fn test_duplicate_payment_hash_one_failure_one_success() {
5283         // Topology : A --> B --> C --> D
5284         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5285         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5286         // we forward one of the payments onwards to D.
5287         let chanmon_cfgs = create_chanmon_cfgs(4);
5288         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5289         // When this test was written, the default base fee floated based on the HTLC count.
5290         // It is now fixed, so we simply set the fee to the expected value here.
5291         let mut config = test_default_channel_config();
5292         config.channel_options.forwarding_fee_base_msat = 196;
5293         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5294                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5295         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5296
5297         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5298         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5299         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5300
5301         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5302         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5303         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5304         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5305         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5306
5307         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5308
5309         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5310         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5311         // script push size limit so that the below script length checks match
5312         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5313         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5314                 .with_features(InvoiceFeatures::known());
5315         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5316         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5317
5318         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5319         assert_eq!(commitment_txn[0].input.len(), 1);
5320         check_spends!(commitment_txn[0], chan_2.3);
5321
5322         mine_transaction(&nodes[1], &commitment_txn[0]);
5323         check_closed_broadcast!(nodes[1], true);
5324         check_added_monitors!(nodes[1], 1);
5325         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5326         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5327
5328         let htlc_timeout_tx;
5329         { // Extract one of the two HTLC-Timeout transaction
5330                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5331                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5332                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5333                 check_spends!(node_txn[0], chan_2.3);
5334
5335                 check_spends!(node_txn[1], commitment_txn[0]);
5336                 assert_eq!(node_txn[1].input.len(), 1);
5337
5338                 if node_txn.len() > 3 {
5339                         check_spends!(node_txn[2], commitment_txn[0]);
5340                         assert_eq!(node_txn[2].input.len(), 1);
5341                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5342
5343                         check_spends!(node_txn[3], commitment_txn[0]);
5344                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5345                 } else {
5346                         check_spends!(node_txn[2], commitment_txn[0]);
5347                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5348                 }
5349
5350                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5351                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5352                 if node_txn.len() > 3 {
5353                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5354                 }
5355                 htlc_timeout_tx = node_txn[1].clone();
5356         }
5357
5358         nodes[2].node.claim_funds(our_payment_preimage);
5359         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5360
5361         mine_transaction(&nodes[2], &commitment_txn[0]);
5362         check_added_monitors!(nodes[2], 2);
5363         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5364         let events = nodes[2].node.get_and_clear_pending_msg_events();
5365         match events[0] {
5366                 MessageSendEvent::UpdateHTLCs { .. } => {},
5367                 _ => panic!("Unexpected event"),
5368         }
5369         match events[1] {
5370                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5371                 _ => panic!("Unexepected event"),
5372         }
5373         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5374         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)
5375         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5376         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5377         assert_eq!(htlc_success_txn[0].input.len(), 1);
5378         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5379         assert_eq!(htlc_success_txn[1].input.len(), 1);
5380         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5381         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5382         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5383         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5384         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5385         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5386
5387         mine_transaction(&nodes[1], &htlc_timeout_tx);
5388         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5389         expect_pending_htlcs_forwardable!(nodes[1]);
5390         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5391         assert!(htlc_updates.update_add_htlcs.is_empty());
5392         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5393         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5394         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5395         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5396         check_added_monitors!(nodes[1], 1);
5397
5398         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5399         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5400         {
5401                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5402         }
5403         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5404
5405         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5406         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5407         // and nodes[2] fee) is rounded down and then claimed in full.
5408         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5409         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5410         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5411         assert!(updates.update_add_htlcs.is_empty());
5412         assert!(updates.update_fail_htlcs.is_empty());
5413         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5414         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5415         assert!(updates.update_fail_malformed_htlcs.is_empty());
5416         check_added_monitors!(nodes[1], 1);
5417
5418         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5419         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5420
5421         let events = nodes[0].node.get_and_clear_pending_events();
5422         match events[0] {
5423                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5424                         assert_eq!(*payment_preimage, our_payment_preimage);
5425                         assert_eq!(*payment_hash, duplicate_payment_hash);
5426                 }
5427                 _ => panic!("Unexpected event"),
5428         }
5429 }
5430
5431 #[test]
5432 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5433         let chanmon_cfgs = create_chanmon_cfgs(2);
5434         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5435         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5436         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5437
5438         // Create some initial channels
5439         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5440
5441         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5442         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5443         assert_eq!(local_txn.len(), 1);
5444         assert_eq!(local_txn[0].input.len(), 1);
5445         check_spends!(local_txn[0], chan_1.3);
5446
5447         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5448         nodes[1].node.claim_funds(payment_preimage);
5449         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5450         check_added_monitors!(nodes[1], 1);
5451
5452         mine_transaction(&nodes[1], &local_txn[0]);
5453         check_added_monitors!(nodes[1], 1);
5454         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5455         let events = nodes[1].node.get_and_clear_pending_msg_events();
5456         match events[0] {
5457                 MessageSendEvent::UpdateHTLCs { .. } => {},
5458                 _ => panic!("Unexpected event"),
5459         }
5460         match events[1] {
5461                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5462                 _ => panic!("Unexepected event"),
5463         }
5464         let node_tx = {
5465                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5466                 assert_eq!(node_txn.len(), 3);
5467                 assert_eq!(node_txn[0], node_txn[2]);
5468                 assert_eq!(node_txn[1], local_txn[0]);
5469                 assert_eq!(node_txn[0].input.len(), 1);
5470                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5471                 check_spends!(node_txn[0], local_txn[0]);
5472                 node_txn[0].clone()
5473         };
5474
5475         mine_transaction(&nodes[1], &node_tx);
5476         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5477
5478         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5479         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5480         assert_eq!(spend_txn.len(), 1);
5481         assert_eq!(spend_txn[0].input.len(), 1);
5482         check_spends!(spend_txn[0], node_tx);
5483         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5484 }
5485
5486 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5487         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5488         // unrevoked commitment transaction.
5489         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5490         // a remote RAA before they could be failed backwards (and combinations thereof).
5491         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5492         // use the same payment hashes.
5493         // Thus, we use a six-node network:
5494         //
5495         // A \         / E
5496         //    - C - D -
5497         // B /         \ F
5498         // And test where C fails back to A/B when D announces its latest commitment transaction
5499         let chanmon_cfgs = create_chanmon_cfgs(6);
5500         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5501         // When this test was written, the default base fee floated based on the HTLC count.
5502         // It is now fixed, so we simply set the fee to the expected value here.
5503         let mut config = test_default_channel_config();
5504         config.channel_options.forwarding_fee_base_msat = 196;
5505         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5506                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5507         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5508
5509         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5510         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5511         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5512         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5513         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5514
5515         // Rebalance and check output sanity...
5516         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5517         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5518         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5519
5520         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5521         // 0th HTLC:
5522         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
5523         // 1st HTLC:
5524         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
5525         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5526         // 2nd HTLC:
5527         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
5528         // 3rd HTLC:
5529         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
5530         // 4th HTLC:
5531         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5532         // 5th HTLC:
5533         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5534         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5535         // 6th HTLC:
5536         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());
5537         // 7th HTLC:
5538         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());
5539
5540         // 8th HTLC:
5541         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5542         // 9th HTLC:
5543         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5544         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
5545
5546         // 10th HTLC:
5547         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
5548         // 11th HTLC:
5549         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5550         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());
5551
5552         // Double-check that six of the new HTLC were added
5553         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5554         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5555         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5556         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5557
5558         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5559         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5560         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5561         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5562         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5563         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5564         check_added_monitors!(nodes[4], 0);
5565         expect_pending_htlcs_forwardable!(nodes[4]);
5566         check_added_monitors!(nodes[4], 1);
5567
5568         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5569         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5570         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5571         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5572         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5573         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5574
5575         // Fail 3rd below-dust and 7th above-dust HTLCs
5576         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5577         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5578         check_added_monitors!(nodes[5], 0);
5579         expect_pending_htlcs_forwardable!(nodes[5]);
5580         check_added_monitors!(nodes[5], 1);
5581
5582         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5583         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5584         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5585         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5586
5587         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5588
5589         expect_pending_htlcs_forwardable!(nodes[3]);
5590         check_added_monitors!(nodes[3], 1);
5591         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5592         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5593         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5594         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5595         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5596         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5597         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5598         if deliver_last_raa {
5599                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5600         } else {
5601                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5602         }
5603
5604         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5605         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5606         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5607         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5608         //
5609         // We now broadcast the latest commitment transaction, which *should* result in failures for
5610         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5611         // the non-broadcast above-dust HTLCs.
5612         //
5613         // Alternatively, we may broadcast the previous commitment transaction, which should only
5614         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5615         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5616
5617         if announce_latest {
5618                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5619         } else {
5620                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5621         }
5622         let events = nodes[2].node.get_and_clear_pending_events();
5623         let close_event = if deliver_last_raa {
5624                 assert_eq!(events.len(), 2);
5625                 events[1].clone()
5626         } else {
5627                 assert_eq!(events.len(), 1);
5628                 events[0].clone()
5629         };
5630         match close_event {
5631                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5632                 _ => panic!("Unexpected event"),
5633         }
5634
5635         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5636         check_closed_broadcast!(nodes[2], true);
5637         if deliver_last_raa {
5638                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5639         } else {
5640                 expect_pending_htlcs_forwardable!(nodes[2]);
5641         }
5642         check_added_monitors!(nodes[2], 3);
5643
5644         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5645         assert_eq!(cs_msgs.len(), 2);
5646         let mut a_done = false;
5647         for msg in cs_msgs {
5648                 match msg {
5649                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5650                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5651                                 // should be failed-backwards here.
5652                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5653                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5654                                         for htlc in &updates.update_fail_htlcs {
5655                                                 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 });
5656                                         }
5657                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5658                                         assert!(!a_done);
5659                                         a_done = true;
5660                                         &nodes[0]
5661                                 } else {
5662                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5663                                         for htlc in &updates.update_fail_htlcs {
5664                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5665                                         }
5666                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5667                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5668                                         &nodes[1]
5669                                 };
5670                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5671                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5672                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5673                                 if announce_latest {
5674                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5675                                         if *node_id == nodes[0].node.get_our_node_id() {
5676                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5677                                         }
5678                                 }
5679                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5680                         },
5681                         _ => panic!("Unexpected event"),
5682                 }
5683         }
5684
5685         let as_events = nodes[0].node.get_and_clear_pending_events();
5686         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5687         let mut as_failds = HashSet::new();
5688         let mut as_updates = 0;
5689         for event in as_events.iter() {
5690                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5691                         assert!(as_failds.insert(*payment_hash));
5692                         if *payment_hash != payment_hash_2 {
5693                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5694                         } else {
5695                                 assert!(!rejected_by_dest);
5696                         }
5697                         if network_update.is_some() {
5698                                 as_updates += 1;
5699                         }
5700                 } else { panic!("Unexpected event"); }
5701         }
5702         assert!(as_failds.contains(&payment_hash_1));
5703         assert!(as_failds.contains(&payment_hash_2));
5704         if announce_latest {
5705                 assert!(as_failds.contains(&payment_hash_3));
5706                 assert!(as_failds.contains(&payment_hash_5));
5707         }
5708         assert!(as_failds.contains(&payment_hash_6));
5709
5710         let bs_events = nodes[1].node.get_and_clear_pending_events();
5711         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5712         let mut bs_failds = HashSet::new();
5713         let mut bs_updates = 0;
5714         for event in bs_events.iter() {
5715                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5716                         assert!(bs_failds.insert(*payment_hash));
5717                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5718                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5719                         } else {
5720                                 assert!(!rejected_by_dest);
5721                         }
5722                         if network_update.is_some() {
5723                                 bs_updates += 1;
5724                         }
5725                 } else { panic!("Unexpected event"); }
5726         }
5727         assert!(bs_failds.contains(&payment_hash_1));
5728         assert!(bs_failds.contains(&payment_hash_2));
5729         if announce_latest {
5730                 assert!(bs_failds.contains(&payment_hash_4));
5731         }
5732         assert!(bs_failds.contains(&payment_hash_5));
5733
5734         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5735         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5736         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5737         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5738         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5739         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5740 }
5741
5742 #[test]
5743 fn test_fail_backwards_latest_remote_announce_a() {
5744         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5745 }
5746
5747 #[test]
5748 fn test_fail_backwards_latest_remote_announce_b() {
5749         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5750 }
5751
5752 #[test]
5753 fn test_fail_backwards_previous_remote_announce() {
5754         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5755         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5756         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5757 }
5758
5759 #[test]
5760 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5761         let chanmon_cfgs = create_chanmon_cfgs(2);
5762         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5763         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5764         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5765
5766         // Create some initial channels
5767         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5768
5769         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5770         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5771         assert_eq!(local_txn[0].input.len(), 1);
5772         check_spends!(local_txn[0], chan_1.3);
5773
5774         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5775         mine_transaction(&nodes[0], &local_txn[0]);
5776         check_closed_broadcast!(nodes[0], true);
5777         check_added_monitors!(nodes[0], 1);
5778         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5779         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5780
5781         let htlc_timeout = {
5782                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5783                 assert_eq!(node_txn.len(), 2);
5784                 check_spends!(node_txn[0], chan_1.3);
5785                 assert_eq!(node_txn[1].input.len(), 1);
5786                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5787                 check_spends!(node_txn[1], local_txn[0]);
5788                 node_txn[1].clone()
5789         };
5790
5791         mine_transaction(&nodes[0], &htlc_timeout);
5792         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5793         expect_payment_failed!(nodes[0], our_payment_hash, true);
5794
5795         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5796         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5797         assert_eq!(spend_txn.len(), 3);
5798         check_spends!(spend_txn[0], local_txn[0]);
5799         assert_eq!(spend_txn[1].input.len(), 1);
5800         check_spends!(spend_txn[1], htlc_timeout);
5801         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5802         assert_eq!(spend_txn[2].input.len(), 2);
5803         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5804         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5805                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5806 }
5807
5808 #[test]
5809 fn test_key_derivation_params() {
5810         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5811         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5812         // let us re-derive the channel key set to then derive a delayed_payment_key.
5813
5814         let chanmon_cfgs = create_chanmon_cfgs(3);
5815
5816         // We manually create the node configuration to backup the seed.
5817         let seed = [42; 32];
5818         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5819         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);
5820         let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5821         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() };
5822         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5823         node_cfgs.remove(0);
5824         node_cfgs.insert(0, node);
5825
5826         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5827         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5828
5829         // Create some initial channels
5830         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5831         // for node 0
5832         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5833         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5834         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5835
5836         // Ensure all nodes are at the same height
5837         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5838         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5839         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5840         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5841
5842         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5843         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5844         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5845         assert_eq!(local_txn_1[0].input.len(), 1);
5846         check_spends!(local_txn_1[0], chan_1.3);
5847
5848         // We check funding pubkey are unique
5849         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]));
5850         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]));
5851         if from_0_funding_key_0 == from_1_funding_key_0
5852             || from_0_funding_key_0 == from_1_funding_key_1
5853             || from_0_funding_key_1 == from_1_funding_key_0
5854             || from_0_funding_key_1 == from_1_funding_key_1 {
5855                 panic!("Funding pubkeys aren't unique");
5856         }
5857
5858         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5859         mine_transaction(&nodes[0], &local_txn_1[0]);
5860         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5861         check_closed_broadcast!(nodes[0], true);
5862         check_added_monitors!(nodes[0], 1);
5863         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5864
5865         let htlc_timeout = {
5866                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5867                 assert_eq!(node_txn[1].input.len(), 1);
5868                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5869                 check_spends!(node_txn[1], local_txn_1[0]);
5870                 node_txn[1].clone()
5871         };
5872
5873         mine_transaction(&nodes[0], &htlc_timeout);
5874         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5875         expect_payment_failed!(nodes[0], our_payment_hash, true);
5876
5877         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5878         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5879         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5880         assert_eq!(spend_txn.len(), 3);
5881         check_spends!(spend_txn[0], local_txn_1[0]);
5882         assert_eq!(spend_txn[1].input.len(), 1);
5883         check_spends!(spend_txn[1], htlc_timeout);
5884         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5885         assert_eq!(spend_txn[2].input.len(), 2);
5886         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5887         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5888                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5889 }
5890
5891 #[test]
5892 fn test_static_output_closing_tx() {
5893         let chanmon_cfgs = create_chanmon_cfgs(2);
5894         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5895         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5896         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5897
5898         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5899
5900         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5901         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5902
5903         mine_transaction(&nodes[0], &closing_tx);
5904         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5905         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5906
5907         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5908         assert_eq!(spend_txn.len(), 1);
5909         check_spends!(spend_txn[0], closing_tx);
5910
5911         mine_transaction(&nodes[1], &closing_tx);
5912         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5913         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5914
5915         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5916         assert_eq!(spend_txn.len(), 1);
5917         check_spends!(spend_txn[0], closing_tx);
5918 }
5919
5920 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5921         let chanmon_cfgs = create_chanmon_cfgs(2);
5922         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5923         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5924         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5925         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5926
5927         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5928
5929         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5930         // present in B's local commitment transaction, but none of A's commitment transactions.
5931         nodes[1].node.claim_funds(payment_preimage);
5932         check_added_monitors!(nodes[1], 1);
5933         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5934
5935         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5936         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5937         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5938
5939         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5940         check_added_monitors!(nodes[0], 1);
5941         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5942         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5943         check_added_monitors!(nodes[1], 1);
5944
5945         let starting_block = nodes[1].best_block_info();
5946         let mut block = Block {
5947                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5948                 txdata: vec![],
5949         };
5950         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5951                 connect_block(&nodes[1], &block);
5952                 block.header.prev_blockhash = block.block_hash();
5953         }
5954         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5955         check_closed_broadcast!(nodes[1], true);
5956         check_added_monitors!(nodes[1], 1);
5957         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5958 }
5959
5960 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5961         let chanmon_cfgs = create_chanmon_cfgs(2);
5962         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5963         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5964         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5965         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5966
5967         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5968         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5969         check_added_monitors!(nodes[0], 1);
5970
5971         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5972
5973         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5974         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5975         // to "time out" the HTLC.
5976
5977         let starting_block = nodes[1].best_block_info();
5978         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5979
5980         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5981                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5982                 header.prev_blockhash = header.block_hash();
5983         }
5984         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5985         check_closed_broadcast!(nodes[0], true);
5986         check_added_monitors!(nodes[0], 1);
5987         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5988 }
5989
5990 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5991         let chanmon_cfgs = create_chanmon_cfgs(3);
5992         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5993         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5994         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5995         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5996
5997         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5998         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5999         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6000         // actually revoked.
6001         let htlc_value = if use_dust { 50000 } else { 3000000 };
6002         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6003         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6004         expect_pending_htlcs_forwardable!(nodes[1]);
6005         check_added_monitors!(nodes[1], 1);
6006
6007         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6008         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6009         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6010         check_added_monitors!(nodes[0], 1);
6011         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6012         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6013         check_added_monitors!(nodes[1], 1);
6014         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6015         check_added_monitors!(nodes[1], 1);
6016         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6017
6018         if check_revoke_no_close {
6019                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6020                 check_added_monitors!(nodes[0], 1);
6021         }
6022
6023         let starting_block = nodes[1].best_block_info();
6024         let mut block = Block {
6025                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6026                 txdata: vec![],
6027         };
6028         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6029                 connect_block(&nodes[0], &block);
6030                 block.header.prev_blockhash = block.block_hash();
6031         }
6032         if !check_revoke_no_close {
6033                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6034                 check_closed_broadcast!(nodes[0], true);
6035                 check_added_monitors!(nodes[0], 1);
6036                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6037         } else {
6038                 let events = nodes[0].node.get_and_clear_pending_events();
6039                 assert_eq!(events.len(), 2);
6040                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6041                         assert_eq!(*payment_hash, our_payment_hash);
6042                 } else { panic!("Unexpected event"); }
6043                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6044                         assert_eq!(*payment_hash, our_payment_hash);
6045                 } else { panic!("Unexpected event"); }
6046         }
6047 }
6048
6049 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6050 // There are only a few cases to test here:
6051 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
6052 //    broadcastable commitment transactions result in channel closure,
6053 //  * its included in an unrevoked-but-previous remote commitment transaction,
6054 //  * its included in the latest remote or local commitment transactions.
6055 // We test each of the three possible commitment transactions individually and use both dust and
6056 // non-dust HTLCs.
6057 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6058 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6059 // tested for at least one of the cases in other tests.
6060 #[test]
6061 fn htlc_claim_single_commitment_only_a() {
6062         do_htlc_claim_local_commitment_only(true);
6063         do_htlc_claim_local_commitment_only(false);
6064
6065         do_htlc_claim_current_remote_commitment_only(true);
6066         do_htlc_claim_current_remote_commitment_only(false);
6067 }
6068
6069 #[test]
6070 fn htlc_claim_single_commitment_only_b() {
6071         do_htlc_claim_previous_remote_commitment_only(true, false);
6072         do_htlc_claim_previous_remote_commitment_only(false, false);
6073         do_htlc_claim_previous_remote_commitment_only(true, true);
6074         do_htlc_claim_previous_remote_commitment_only(false, true);
6075 }
6076
6077 #[test]
6078 #[should_panic]
6079 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6080         let chanmon_cfgs = create_chanmon_cfgs(2);
6081         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6082         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6083         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6084         // Force duplicate randomness for every get-random call
6085         for node in nodes.iter() {
6086                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6087         }
6088
6089         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6090         let channel_value_satoshis=10000;
6091         let push_msat=10001;
6092         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6093         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6094         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6095         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6096
6097         // Create a second channel with the same random values. This used to panic due to a colliding
6098         // channel_id, but now panics due to a colliding outbound SCID alias.
6099         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6100 }
6101
6102 #[test]
6103 fn bolt2_open_channel_sending_node_checks_part2() {
6104         let chanmon_cfgs = create_chanmon_cfgs(2);
6105         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6106         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6107         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6108
6109         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6110         let channel_value_satoshis=2^24;
6111         let push_msat=10001;
6112         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6113
6114         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6115         let channel_value_satoshis=10000;
6116         // Test when push_msat is equal to 1000 * funding_satoshis.
6117         let push_msat=1000*channel_value_satoshis+1;
6118         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6119
6120         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6121         let channel_value_satoshis=10000;
6122         let push_msat=10001;
6123         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
6124         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6125         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6126
6127         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6128         // 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
6129         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6130
6131         // 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.
6132         assert!(BREAKDOWN_TIMEOUT>0);
6133         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6134
6135         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6136         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6137         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6138
6139         // 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.
6140         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6141         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6142         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6143         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6144         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6145 }
6146
6147 #[test]
6148 fn bolt2_open_channel_sane_dust_limit() {
6149         let chanmon_cfgs = create_chanmon_cfgs(2);
6150         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6151         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6152         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6153
6154         let channel_value_satoshis=1000000;
6155         let push_msat=10001;
6156         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6157         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6158         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6159         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6160
6161         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6162         let events = nodes[1].node.get_and_clear_pending_msg_events();
6163         let err_msg = match events[0] {
6164                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6165                         msg.clone()
6166                 },
6167                 _ => panic!("Unexpected event"),
6168         };
6169         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6170 }
6171
6172 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6173 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6174 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6175 // is no longer affordable once it's freed.
6176 #[test]
6177 fn test_fail_holding_cell_htlc_upon_free() {
6178         let chanmon_cfgs = create_chanmon_cfgs(2);
6179         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6180         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6181         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6182         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6183
6184         // First nodes[0] generates an update_fee, setting the channel's
6185         // pending_update_fee.
6186         {
6187                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6188                 *feerate_lock += 20;
6189         }
6190         nodes[0].node.timer_tick_occurred();
6191         check_added_monitors!(nodes[0], 1);
6192
6193         let events = nodes[0].node.get_and_clear_pending_msg_events();
6194         assert_eq!(events.len(), 1);
6195         let (update_msg, commitment_signed) = match events[0] {
6196                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6197                         (update_fee.as_ref(), commitment_signed)
6198                 },
6199                 _ => panic!("Unexpected event"),
6200         };
6201
6202         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6203
6204         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6205         let channel_reserve = chan_stat.channel_reserve_msat;
6206         let feerate = get_feerate!(nodes[0], chan.2);
6207         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6208
6209         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6210         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6211         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6212
6213         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6214         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6215         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6216         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6217
6218         // Flush the pending fee update.
6219         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6220         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6221         check_added_monitors!(nodes[1], 1);
6222         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6223         check_added_monitors!(nodes[0], 1);
6224
6225         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6226         // HTLC, but now that the fee has been raised the payment will now fail, causing
6227         // us to surface its failure to the user.
6228         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6229         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6230         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);
6231         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 {}",
6232                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6233         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6234
6235         // Check that the payment failed to be sent out.
6236         let events = nodes[0].node.get_and_clear_pending_events();
6237         assert_eq!(events.len(), 1);
6238         match &events[0] {
6239                 &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, .. } => {
6240                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6241                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6242                         assert_eq!(*rejected_by_dest, false);
6243                         assert_eq!(*all_paths_failed, true);
6244                         assert_eq!(*network_update, None);
6245                         assert_eq!(*short_channel_id, None);
6246                         assert_eq!(*error_code, None);
6247                         assert_eq!(*error_data, None);
6248                 },
6249                 _ => panic!("Unexpected event"),
6250         }
6251 }
6252
6253 // Test that if multiple HTLCs are released from the holding cell and one is
6254 // valid but the other is no longer valid upon release, the valid HTLC can be
6255 // successfully completed while the other one fails as expected.
6256 #[test]
6257 fn test_free_and_fail_holding_cell_htlcs() {
6258         let chanmon_cfgs = create_chanmon_cfgs(2);
6259         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6260         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6261         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6262         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6263
6264         // First nodes[0] generates an update_fee, setting the channel's
6265         // pending_update_fee.
6266         {
6267                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6268                 *feerate_lock += 200;
6269         }
6270         nodes[0].node.timer_tick_occurred();
6271         check_added_monitors!(nodes[0], 1);
6272
6273         let events = nodes[0].node.get_and_clear_pending_msg_events();
6274         assert_eq!(events.len(), 1);
6275         let (update_msg, commitment_signed) = match events[0] {
6276                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6277                         (update_fee.as_ref(), commitment_signed)
6278                 },
6279                 _ => panic!("Unexpected event"),
6280         };
6281
6282         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6283
6284         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6285         let channel_reserve = chan_stat.channel_reserve_msat;
6286         let feerate = get_feerate!(nodes[0], chan.2);
6287         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6288
6289         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6290         let amt_1 = 20000;
6291         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6292         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6293         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6294
6295         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6296         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6297         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6298         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6299         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6300         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6301         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6302
6303         // Flush the pending fee update.
6304         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6305         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6306         check_added_monitors!(nodes[1], 1);
6307         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6308         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6309         check_added_monitors!(nodes[0], 2);
6310
6311         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6312         // but now that the fee has been raised the second payment will now fail, causing us
6313         // to surface its failure to the user. The first payment should succeed.
6314         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6315         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6316         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);
6317         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 {}",
6318                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6319         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6320
6321         // Check that the second payment failed to be sent out.
6322         let events = nodes[0].node.get_and_clear_pending_events();
6323         assert_eq!(events.len(), 1);
6324         match &events[0] {
6325                 &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, .. } => {
6326                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6327                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6328                         assert_eq!(*rejected_by_dest, false);
6329                         assert_eq!(*all_paths_failed, true);
6330                         assert_eq!(*network_update, None);
6331                         assert_eq!(*short_channel_id, None);
6332                         assert_eq!(*error_code, None);
6333                         assert_eq!(*error_data, None);
6334                 },
6335                 _ => panic!("Unexpected event"),
6336         }
6337
6338         // Complete the first payment and the RAA from the fee update.
6339         let (payment_event, send_raa_event) = {
6340                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6341                 assert_eq!(msgs.len(), 2);
6342                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6343         };
6344         let raa = match send_raa_event {
6345                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6346                 _ => panic!("Unexpected event"),
6347         };
6348         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6349         check_added_monitors!(nodes[1], 1);
6350         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6351         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6352         let events = nodes[1].node.get_and_clear_pending_events();
6353         assert_eq!(events.len(), 1);
6354         match events[0] {
6355                 Event::PendingHTLCsForwardable { .. } => {},
6356                 _ => panic!("Unexpected event"),
6357         }
6358         nodes[1].node.process_pending_htlc_forwards();
6359         let events = nodes[1].node.get_and_clear_pending_events();
6360         assert_eq!(events.len(), 1);
6361         match events[0] {
6362                 Event::PaymentReceived { .. } => {},
6363                 _ => panic!("Unexpected event"),
6364         }
6365         nodes[1].node.claim_funds(payment_preimage_1);
6366         check_added_monitors!(nodes[1], 1);
6367         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6368
6369         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6370         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6371         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6372         expect_payment_sent!(nodes[0], payment_preimage_1);
6373 }
6374
6375 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6376 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6377 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6378 // once it's freed.
6379 #[test]
6380 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6381         let chanmon_cfgs = create_chanmon_cfgs(3);
6382         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6383         // When this test was written, the default base fee floated based on the HTLC count.
6384         // It is now fixed, so we simply set the fee to the expected value here.
6385         let mut config = test_default_channel_config();
6386         config.channel_options.forwarding_fee_base_msat = 196;
6387         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6388         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6389         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6390         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6391
6392         // First nodes[1] generates an update_fee, setting the channel's
6393         // pending_update_fee.
6394         {
6395                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6396                 *feerate_lock += 20;
6397         }
6398         nodes[1].node.timer_tick_occurred();
6399         check_added_monitors!(nodes[1], 1);
6400
6401         let events = nodes[1].node.get_and_clear_pending_msg_events();
6402         assert_eq!(events.len(), 1);
6403         let (update_msg, commitment_signed) = match events[0] {
6404                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6405                         (update_fee.as_ref(), commitment_signed)
6406                 },
6407                 _ => panic!("Unexpected event"),
6408         };
6409
6410         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6411
6412         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6413         let channel_reserve = chan_stat.channel_reserve_msat;
6414         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6415         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6416
6417         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6418         let feemsat = 239;
6419         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6420         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6421         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6422         let payment_event = {
6423                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6424                 check_added_monitors!(nodes[0], 1);
6425
6426                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6427                 assert_eq!(events.len(), 1);
6428
6429                 SendEvent::from_event(events.remove(0))
6430         };
6431         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6432         check_added_monitors!(nodes[1], 0);
6433         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6434         expect_pending_htlcs_forwardable!(nodes[1]);
6435
6436         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6437         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6438
6439         // Flush the pending fee update.
6440         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6441         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6442         check_added_monitors!(nodes[2], 1);
6443         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6444         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6445         check_added_monitors!(nodes[1], 2);
6446
6447         // A final RAA message is generated to finalize the fee update.
6448         let events = nodes[1].node.get_and_clear_pending_msg_events();
6449         assert_eq!(events.len(), 1);
6450
6451         let raa_msg = match &events[0] {
6452                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6453                         msg.clone()
6454                 },
6455                 _ => panic!("Unexpected event"),
6456         };
6457
6458         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6459         check_added_monitors!(nodes[2], 1);
6460         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6461
6462         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6463         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6464         assert_eq!(process_htlc_forwards_event.len(), 1);
6465         match &process_htlc_forwards_event[0] {
6466                 &Event::PendingHTLCsForwardable { .. } => {},
6467                 _ => panic!("Unexpected event"),
6468         }
6469
6470         // In response, we call ChannelManager's process_pending_htlc_forwards
6471         nodes[1].node.process_pending_htlc_forwards();
6472         check_added_monitors!(nodes[1], 1);
6473
6474         // This causes the HTLC to be failed backwards.
6475         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6476         assert_eq!(fail_event.len(), 1);
6477         let (fail_msg, commitment_signed) = match &fail_event[0] {
6478                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6479                         assert_eq!(updates.update_add_htlcs.len(), 0);
6480                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6481                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6482                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6483                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6484                 },
6485                 _ => panic!("Unexpected event"),
6486         };
6487
6488         // Pass the failure messages back to nodes[0].
6489         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6490         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6491
6492         // Complete the HTLC failure+removal process.
6493         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6494         check_added_monitors!(nodes[0], 1);
6495         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6496         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6497         check_added_monitors!(nodes[1], 2);
6498         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6499         assert_eq!(final_raa_event.len(), 1);
6500         let raa = match &final_raa_event[0] {
6501                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6502                 _ => panic!("Unexpected event"),
6503         };
6504         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6505         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6506         check_added_monitors!(nodes[0], 1);
6507 }
6508
6509 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6510 // 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.
6511 //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.
6512
6513 #[test]
6514 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6515         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6516         let chanmon_cfgs = create_chanmon_cfgs(2);
6517         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6518         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6519         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6520         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6521
6522         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6523         route.paths[0][0].fee_msat = 100;
6524
6525         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6526                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6527         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6528         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6529 }
6530
6531 #[test]
6532 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6533         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6534         let chanmon_cfgs = create_chanmon_cfgs(2);
6535         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6536         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6537         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6538         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6539
6540         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6541         route.paths[0][0].fee_msat = 0;
6542         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6543                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6544
6545         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6546         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6547 }
6548
6549 #[test]
6550 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6551         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6552         let chanmon_cfgs = create_chanmon_cfgs(2);
6553         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6554         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6555         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6556         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6557
6558         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6559         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6560         check_added_monitors!(nodes[0], 1);
6561         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6562         updates.update_add_htlcs[0].amount_msat = 0;
6563
6564         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6565         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6566         check_closed_broadcast!(nodes[1], true).unwrap();
6567         check_added_monitors!(nodes[1], 1);
6568         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6569 }
6570
6571 #[test]
6572 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6573         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6574         //It is enforced when constructing a route.
6575         let chanmon_cfgs = create_chanmon_cfgs(2);
6576         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6577         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6578         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6579         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6580
6581         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6582                 .with_features(InvoiceFeatures::known());
6583         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6584         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6585         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6586                 assert_eq!(err, &"Channel CLTV overflowed?"));
6587 }
6588
6589 #[test]
6590 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6591         //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.
6592         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6593         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6594         let chanmon_cfgs = create_chanmon_cfgs(2);
6595         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6596         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6597         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6598         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6599         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6600
6601         for i in 0..max_accepted_htlcs {
6602                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6603                 let payment_event = {
6604                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6605                         check_added_monitors!(nodes[0], 1);
6606
6607                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6608                         assert_eq!(events.len(), 1);
6609                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6610                                 assert_eq!(htlcs[0].htlc_id, i);
6611                         } else {
6612                                 assert!(false);
6613                         }
6614                         SendEvent::from_event(events.remove(0))
6615                 };
6616                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6617                 check_added_monitors!(nodes[1], 0);
6618                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6619
6620                 expect_pending_htlcs_forwardable!(nodes[1]);
6621                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6622         }
6623         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6624         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6625                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6626
6627         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6628         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6629 }
6630
6631 #[test]
6632 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6633         //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.
6634         let chanmon_cfgs = create_chanmon_cfgs(2);
6635         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6636         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6637         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6638         let channel_value = 100000;
6639         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6640         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6641
6642         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6643
6644         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6645         // Manually create a route over our max in flight (which our router normally automatically
6646         // limits us to.
6647         route.paths[0][0].fee_msat =  max_in_flight + 1;
6648         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6649                 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)));
6650
6651         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6652         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);
6653
6654         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6655 }
6656
6657 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6658 #[test]
6659 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6660         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6661         let chanmon_cfgs = create_chanmon_cfgs(2);
6662         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6663         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6664         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6665         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6666         let htlc_minimum_msat: u64;
6667         {
6668                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6669                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6670                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6671         }
6672
6673         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6674         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6675         check_added_monitors!(nodes[0], 1);
6676         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6677         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6678         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6679         assert!(nodes[1].node.list_channels().is_empty());
6680         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6681         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()));
6682         check_added_monitors!(nodes[1], 1);
6683         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6684 }
6685
6686 #[test]
6687 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6688         //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
6689         let chanmon_cfgs = create_chanmon_cfgs(2);
6690         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6691         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6692         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6693         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6694
6695         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6696         let channel_reserve = chan_stat.channel_reserve_msat;
6697         let feerate = get_feerate!(nodes[0], chan.2);
6698         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6699         // The 2* and +1 are for the fee spike reserve.
6700         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6701
6702         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6703         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6704         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6705         check_added_monitors!(nodes[0], 1);
6706         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6707
6708         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6709         // at this time channel-initiatee receivers are not required to enforce that senders
6710         // respect the fee_spike_reserve.
6711         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6712         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6713
6714         assert!(nodes[1].node.list_channels().is_empty());
6715         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6716         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6717         check_added_monitors!(nodes[1], 1);
6718         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6719 }
6720
6721 #[test]
6722 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6723         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6724         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6725         let chanmon_cfgs = create_chanmon_cfgs(2);
6726         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6727         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6728         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6729         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6730
6731         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6732         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6733         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6734         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6735         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6736         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6737
6738         let mut msg = msgs::UpdateAddHTLC {
6739                 channel_id: chan.2,
6740                 htlc_id: 0,
6741                 amount_msat: 1000,
6742                 payment_hash: our_payment_hash,
6743                 cltv_expiry: htlc_cltv,
6744                 onion_routing_packet: onion_packet.clone(),
6745         };
6746
6747         for i in 0..super::channel::OUR_MAX_HTLCS {
6748                 msg.htlc_id = i as u64;
6749                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6750         }
6751         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6752         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6753
6754         assert!(nodes[1].node.list_channels().is_empty());
6755         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6756         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6757         check_added_monitors!(nodes[1], 1);
6758         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6759 }
6760
6761 #[test]
6762 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6763         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6764         let chanmon_cfgs = create_chanmon_cfgs(2);
6765         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6766         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6767         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6768         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6769
6770         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6771         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6772         check_added_monitors!(nodes[0], 1);
6773         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6774         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6775         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6776
6777         assert!(nodes[1].node.list_channels().is_empty());
6778         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6779         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6780         check_added_monitors!(nodes[1], 1);
6781         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6782 }
6783
6784 #[test]
6785 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6786         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6787         let chanmon_cfgs = create_chanmon_cfgs(2);
6788         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6789         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6790         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6791
6792         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6793         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6794         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6795         check_added_monitors!(nodes[0], 1);
6796         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6797         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6798         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6799
6800         assert!(nodes[1].node.list_channels().is_empty());
6801         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6802         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6803         check_added_monitors!(nodes[1], 1);
6804         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6805 }
6806
6807 #[test]
6808 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6809         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6810         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6811         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6812         let chanmon_cfgs = create_chanmon_cfgs(2);
6813         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6814         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6815         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6816
6817         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6818         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6819         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6820         check_added_monitors!(nodes[0], 1);
6821         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6822         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6823
6824         //Disconnect and Reconnect
6825         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6826         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6827         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6828         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6829         assert_eq!(reestablish_1.len(), 1);
6830         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6831         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6832         assert_eq!(reestablish_2.len(), 1);
6833         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6834         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6835         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6836         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6837
6838         //Resend HTLC
6839         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6840         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6841         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6842         check_added_monitors!(nodes[1], 1);
6843         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6844
6845         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6846
6847         assert!(nodes[1].node.list_channels().is_empty());
6848         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6849         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6850         check_added_monitors!(nodes[1], 1);
6851         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6852 }
6853
6854 #[test]
6855 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6856         //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.
6857
6858         let chanmon_cfgs = create_chanmon_cfgs(2);
6859         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6860         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6861         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6862         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6863         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6864         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6865
6866         check_added_monitors!(nodes[0], 1);
6867         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6868         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6869
6870         let update_msg = msgs::UpdateFulfillHTLC{
6871                 channel_id: chan.2,
6872                 htlc_id: 0,
6873                 payment_preimage: our_payment_preimage,
6874         };
6875
6876         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6877
6878         assert!(nodes[0].node.list_channels().is_empty());
6879         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6880         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()));
6881         check_added_monitors!(nodes[0], 1);
6882         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6883 }
6884
6885 #[test]
6886 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6887         //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.
6888
6889         let chanmon_cfgs = create_chanmon_cfgs(2);
6890         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6891         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6892         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6893         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6894
6895         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6896         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6897         check_added_monitors!(nodes[0], 1);
6898         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6899         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6900
6901         let update_msg = msgs::UpdateFailHTLC{
6902                 channel_id: chan.2,
6903                 htlc_id: 0,
6904                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6905         };
6906
6907         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6908
6909         assert!(nodes[0].node.list_channels().is_empty());
6910         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6911         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()));
6912         check_added_monitors!(nodes[0], 1);
6913         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6914 }
6915
6916 #[test]
6917 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6918         //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.
6919
6920         let chanmon_cfgs = create_chanmon_cfgs(2);
6921         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6922         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6923         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6924         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6925
6926         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6927         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6928         check_added_monitors!(nodes[0], 1);
6929         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6930         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6931         let update_msg = msgs::UpdateFailMalformedHTLC{
6932                 channel_id: chan.2,
6933                 htlc_id: 0,
6934                 sha256_of_onion: [1; 32],
6935                 failure_code: 0x8000,
6936         };
6937
6938         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6939
6940         assert!(nodes[0].node.list_channels().is_empty());
6941         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6942         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()));
6943         check_added_monitors!(nodes[0], 1);
6944         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6945 }
6946
6947 #[test]
6948 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6949         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6950
6951         let chanmon_cfgs = create_chanmon_cfgs(2);
6952         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6953         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6954         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6955         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6956
6957         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6958
6959         nodes[1].node.claim_funds(our_payment_preimage);
6960         check_added_monitors!(nodes[1], 1);
6961         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6962
6963         let events = nodes[1].node.get_and_clear_pending_msg_events();
6964         assert_eq!(events.len(), 1);
6965         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6966                 match events[0] {
6967                         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, .. } } => {
6968                                 assert!(update_add_htlcs.is_empty());
6969                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6970                                 assert!(update_fail_htlcs.is_empty());
6971                                 assert!(update_fail_malformed_htlcs.is_empty());
6972                                 assert!(update_fee.is_none());
6973                                 update_fulfill_htlcs[0].clone()
6974                         },
6975                         _ => panic!("Unexpected event"),
6976                 }
6977         };
6978
6979         update_fulfill_msg.htlc_id = 1;
6980
6981         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6982
6983         assert!(nodes[0].node.list_channels().is_empty());
6984         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6985         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6986         check_added_monitors!(nodes[0], 1);
6987         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6988 }
6989
6990 #[test]
6991 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6992         //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.
6993
6994         let chanmon_cfgs = create_chanmon_cfgs(2);
6995         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6996         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6997         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6998         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6999
7000         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
7001
7002         nodes[1].node.claim_funds(our_payment_preimage);
7003         check_added_monitors!(nodes[1], 1);
7004         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7005
7006         let events = nodes[1].node.get_and_clear_pending_msg_events();
7007         assert_eq!(events.len(), 1);
7008         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7009                 match events[0] {
7010                         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, .. } } => {
7011                                 assert!(update_add_htlcs.is_empty());
7012                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7013                                 assert!(update_fail_htlcs.is_empty());
7014                                 assert!(update_fail_malformed_htlcs.is_empty());
7015                                 assert!(update_fee.is_none());
7016                                 update_fulfill_htlcs[0].clone()
7017                         },
7018                         _ => panic!("Unexpected event"),
7019                 }
7020         };
7021
7022         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7023
7024         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7025
7026         assert!(nodes[0].node.list_channels().is_empty());
7027         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7028         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7029         check_added_monitors!(nodes[0], 1);
7030         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7031 }
7032
7033 #[test]
7034 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7035         //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.
7036
7037         let chanmon_cfgs = create_chanmon_cfgs(2);
7038         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7039         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7040         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7041         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7042
7043         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7044         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7045         check_added_monitors!(nodes[0], 1);
7046
7047         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7048         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7049
7050         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7051         check_added_monitors!(nodes[1], 0);
7052         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7053
7054         let events = nodes[1].node.get_and_clear_pending_msg_events();
7055
7056         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7057                 match events[0] {
7058                         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, .. } } => {
7059                                 assert!(update_add_htlcs.is_empty());
7060                                 assert!(update_fulfill_htlcs.is_empty());
7061                                 assert!(update_fail_htlcs.is_empty());
7062                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7063                                 assert!(update_fee.is_none());
7064                                 update_fail_malformed_htlcs[0].clone()
7065                         },
7066                         _ => panic!("Unexpected event"),
7067                 }
7068         };
7069         update_msg.failure_code &= !0x8000;
7070         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7071
7072         assert!(nodes[0].node.list_channels().is_empty());
7073         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7074         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7075         check_added_monitors!(nodes[0], 1);
7076         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7077 }
7078
7079 #[test]
7080 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7081         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7082         //    * 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.
7083
7084         let chanmon_cfgs = create_chanmon_cfgs(3);
7085         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7086         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7087         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7088         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7089         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7090
7091         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7092
7093         //First hop
7094         let mut payment_event = {
7095                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7096                 check_added_monitors!(nodes[0], 1);
7097                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7098                 assert_eq!(events.len(), 1);
7099                 SendEvent::from_event(events.remove(0))
7100         };
7101         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7102         check_added_monitors!(nodes[1], 0);
7103         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7104         expect_pending_htlcs_forwardable!(nodes[1]);
7105         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7106         assert_eq!(events_2.len(), 1);
7107         check_added_monitors!(nodes[1], 1);
7108         payment_event = SendEvent::from_event(events_2.remove(0));
7109         assert_eq!(payment_event.msgs.len(), 1);
7110
7111         //Second Hop
7112         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7113         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7114         check_added_monitors!(nodes[2], 0);
7115         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7116
7117         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7118         assert_eq!(events_3.len(), 1);
7119         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7120                 match events_3[0] {
7121                         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 } } => {
7122                                 assert!(update_add_htlcs.is_empty());
7123                                 assert!(update_fulfill_htlcs.is_empty());
7124                                 assert!(update_fail_htlcs.is_empty());
7125                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7126                                 assert!(update_fee.is_none());
7127                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7128                         },
7129                         _ => panic!("Unexpected event"),
7130                 }
7131         };
7132
7133         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7134
7135         check_added_monitors!(nodes[1], 0);
7136         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7137         expect_pending_htlcs_forwardable!(nodes[1]);
7138         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7139         assert_eq!(events_4.len(), 1);
7140
7141         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7142         match events_4[0] {
7143                 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, .. } } => {
7144                         assert!(update_add_htlcs.is_empty());
7145                         assert!(update_fulfill_htlcs.is_empty());
7146                         assert_eq!(update_fail_htlcs.len(), 1);
7147                         assert!(update_fail_malformed_htlcs.is_empty());
7148                         assert!(update_fee.is_none());
7149                 },
7150                 _ => panic!("Unexpected event"),
7151         };
7152
7153         check_added_monitors!(nodes[1], 1);
7154 }
7155
7156 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7157         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7158         // 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
7159         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7160
7161         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7162         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7163         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7164         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7165         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7166         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7167
7168         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7169
7170         // We route 2 dust-HTLCs between A and B
7171         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7172         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7173         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7174
7175         // Cache one local commitment tx as previous
7176         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7177
7178         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7179         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7180         check_added_monitors!(nodes[1], 0);
7181         expect_pending_htlcs_forwardable!(nodes[1]);
7182         check_added_monitors!(nodes[1], 1);
7183
7184         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7185         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7186         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7187         check_added_monitors!(nodes[0], 1);
7188
7189         // Cache one local commitment tx as lastest
7190         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7191
7192         let events = nodes[0].node.get_and_clear_pending_msg_events();
7193         match events[0] {
7194                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7195                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7196                 },
7197                 _ => panic!("Unexpected event"),
7198         }
7199         match events[1] {
7200                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7201                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7202                 },
7203                 _ => panic!("Unexpected event"),
7204         }
7205
7206         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7207         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7208         if announce_latest {
7209                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7210         } else {
7211                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7212         }
7213
7214         check_closed_broadcast!(nodes[0], true);
7215         check_added_monitors!(nodes[0], 1);
7216         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7217
7218         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7219         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7220         let events = nodes[0].node.get_and_clear_pending_events();
7221         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7222         assert_eq!(events.len(), 2);
7223         let mut first_failed = false;
7224         for event in events {
7225                 match event {
7226                         Event::PaymentPathFailed { payment_hash, .. } => {
7227                                 if payment_hash == payment_hash_1 {
7228                                         assert!(!first_failed);
7229                                         first_failed = true;
7230                                 } else {
7231                                         assert_eq!(payment_hash, payment_hash_2);
7232                                 }
7233                         }
7234                         _ => panic!("Unexpected event"),
7235                 }
7236         }
7237 }
7238
7239 #[test]
7240 fn test_failure_delay_dust_htlc_local_commitment() {
7241         do_test_failure_delay_dust_htlc_local_commitment(true);
7242         do_test_failure_delay_dust_htlc_local_commitment(false);
7243 }
7244
7245 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7246         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7247         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7248         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7249         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7250         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7251         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7252
7253         let chanmon_cfgs = create_chanmon_cfgs(3);
7254         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7255         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7256         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7257         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7258
7259         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7260
7261         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7262         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7263
7264         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7265         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7266
7267         // We revoked bs_commitment_tx
7268         if revoked {
7269                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7270                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7271         }
7272
7273         let mut timeout_tx = Vec::new();
7274         if local {
7275                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7276                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7277                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7278                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7279                 expect_payment_failed!(nodes[0], dust_hash, true);
7280
7281                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7282                 check_closed_broadcast!(nodes[0], true);
7283                 check_added_monitors!(nodes[0], 1);
7284                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7285                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7286                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7287                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7288                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7289                 mine_transaction(&nodes[0], &timeout_tx[0]);
7290                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7291                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7292         } else {
7293                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7294                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7295                 check_closed_broadcast!(nodes[0], true);
7296                 check_added_monitors!(nodes[0], 1);
7297                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7298                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7299
7300                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7301                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7302                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7303                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7304                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7305                 // dust HTLC should have been failed.
7306                 expect_payment_failed!(nodes[0], dust_hash, true);
7307
7308                 if !revoked {
7309                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7310                 } else {
7311                         assert_eq!(timeout_tx[0].lock_time, 0);
7312                 }
7313                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7314                 mine_transaction(&nodes[0], &timeout_tx[0]);
7315                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7316                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7317                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7318         }
7319 }
7320
7321 #[test]
7322 fn test_sweep_outbound_htlc_failure_update() {
7323         do_test_sweep_outbound_htlc_failure_update(false, true);
7324         do_test_sweep_outbound_htlc_failure_update(false, false);
7325         do_test_sweep_outbound_htlc_failure_update(true, false);
7326 }
7327
7328 #[test]
7329 fn test_user_configurable_csv_delay() {
7330         // We test our channel constructors yield errors when we pass them absurd csv delay
7331
7332         let mut low_our_to_self_config = UserConfig::default();
7333         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7334         let mut high_their_to_self_config = UserConfig::default();
7335         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7336         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7337         let chanmon_cfgs = create_chanmon_cfgs(2);
7338         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7339         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7340         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7341
7342         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7343         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7344                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7345                 &low_our_to_self_config, 0, 42)
7346         {
7347                 match error {
7348                         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())); },
7349                         _ => panic!("Unexpected event"),
7350                 }
7351         } else { assert!(false) }
7352
7353         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7354         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7355         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7356         open_channel.to_self_delay = 200;
7357         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7358                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7359                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7360         {
7361                 match error {
7362                         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()));  },
7363                         _ => panic!("Unexpected event"),
7364                 }
7365         } else { assert!(false); }
7366
7367         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7368         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7369         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()));
7370         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7371         accept_channel.to_self_delay = 200;
7372         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7373         let reason_msg;
7374         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7375                 match action {
7376                         &ErrorAction::SendErrorMessage { ref msg } => {
7377                                 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()));
7378                                 reason_msg = msg.data.clone();
7379                         },
7380                         _ => { panic!(); }
7381                 }
7382         } else { panic!(); }
7383         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7384
7385         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7386         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7387         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7388         open_channel.to_self_delay = 200;
7389         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7390                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7391                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7392         {
7393                 match error {
7394                         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())); },
7395                         _ => panic!("Unexpected event"),
7396                 }
7397         } else { assert!(false); }
7398 }
7399
7400 #[test]
7401 fn test_data_loss_protect() {
7402         // We want to be sure that :
7403         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7404         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7405         // * we close channel in case of detecting other being fallen behind
7406         // * we are able to claim our own outputs thanks to to_remote being static
7407         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7408         let persister;
7409         let logger;
7410         let fee_estimator;
7411         let tx_broadcaster;
7412         let chain_source;
7413         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7414         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7415         // during signing due to revoked tx
7416         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7417         let keys_manager = &chanmon_cfgs[0].keys_manager;
7418         let monitor;
7419         let node_state_0;
7420         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7421         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7422         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7423
7424         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7425
7426         // Cache node A state before any channel update
7427         let previous_node_state = nodes[0].node.encode();
7428         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7429         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7430
7431         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7432         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7433
7434         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7435         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7436
7437         // Restore node A from previous state
7438         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7439         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7440         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7441         tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7442         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7443         persister = test_utils::TestPersister::new();
7444         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7445         node_state_0 = {
7446                 let mut channel_monitors = HashMap::new();
7447                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7448                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7449                         keys_manager: keys_manager,
7450                         fee_estimator: &fee_estimator,
7451                         chain_monitor: &monitor,
7452                         logger: &logger,
7453                         tx_broadcaster: &tx_broadcaster,
7454                         default_config: UserConfig::default(),
7455                         channel_monitors,
7456                 }).unwrap().1
7457         };
7458         nodes[0].node = &node_state_0;
7459         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7460         nodes[0].chain_monitor = &monitor;
7461         nodes[0].chain_source = &chain_source;
7462
7463         check_added_monitors!(nodes[0], 1);
7464
7465         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7466         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7467
7468         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7469
7470         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7471         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7472         check_added_monitors!(nodes[0], 1);
7473
7474         {
7475                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7476                 assert_eq!(node_txn.len(), 0);
7477         }
7478
7479         let mut reestablish_1 = Vec::with_capacity(1);
7480         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7481                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7482                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7483                         reestablish_1.push(msg.clone());
7484                 } else 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, "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can't do any automated broadcasting");
7489                                 },
7490                                 _ => panic!("Unexpected event!"),
7491                         }
7492                 } else {
7493                         panic!("Unexpected event")
7494                 }
7495         }
7496
7497         // Check we close channel detecting A is fallen-behind
7498         // Check that we sent the warning message when we detected that A has fallen behind,
7499         // and give the possibility for A to recover from the warning.
7500         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7501         let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7502         assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7503
7504         // Check A is able to claim to_remote output
7505         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7506         // The node B should not broadcast the transaction to force close the channel!
7507         assert!(node_txn.is_empty());
7508         // B should now detect that there is something wrong and should force close the channel.
7509         let exp_err = "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can\'t do any automated broadcasting";
7510         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: exp_err.to_string() });
7511
7512         // after the warning message sent by B, we should not able to
7513         // use the channel, or reconnect with success to the channel.
7514         assert!(nodes[0].node.list_usable_channels().is_empty());
7515         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7516         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7517         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7518
7519         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7520         let mut err_msgs_0 = Vec::with_capacity(1);
7521         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7522                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7523                         match action {
7524                                 &ErrorAction::SendErrorMessage { ref msg } => {
7525                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7526                                         err_msgs_0.push(msg.clone());
7527                                 },
7528                                 _ => panic!("Unexpected event!"),
7529                         }
7530                 } else {
7531                         panic!("Unexpected event!");
7532                 }
7533         }
7534         assert_eq!(err_msgs_0.len(), 1);
7535         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7536         assert!(nodes[1].node.list_usable_channels().is_empty());
7537         check_added_monitors!(nodes[1], 1);
7538         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7539         check_closed_broadcast!(nodes[1], false);
7540 }
7541
7542 #[test]
7543 fn test_check_htlc_underpaying() {
7544         // Send payment through A -> B but A is maliciously
7545         // sending a probe payment (i.e less than expected value0
7546         // to B, B should refuse payment.
7547
7548         let chanmon_cfgs = create_chanmon_cfgs(2);
7549         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7550         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7551         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7552
7553         // Create some initial channels
7554         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7555
7556         let scorer = test_utils::TestScorer::with_penalty(0);
7557         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7558         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7559         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();
7560         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7561         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7562         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7563         check_added_monitors!(nodes[0], 1);
7564
7565         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7566         assert_eq!(events.len(), 1);
7567         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7568         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7569         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7570
7571         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7572         // and then will wait a second random delay before failing the HTLC back:
7573         expect_pending_htlcs_forwardable!(nodes[1]);
7574         expect_pending_htlcs_forwardable!(nodes[1]);
7575
7576         // Node 3 is expecting payment of 100_000 but received 10_000,
7577         // it should fail htlc like we didn't know the preimage.
7578         nodes[1].node.process_pending_htlc_forwards();
7579
7580         let events = nodes[1].node.get_and_clear_pending_msg_events();
7581         assert_eq!(events.len(), 1);
7582         let (update_fail_htlc, commitment_signed) = match events[0] {
7583                 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 } } => {
7584                         assert!(update_add_htlcs.is_empty());
7585                         assert!(update_fulfill_htlcs.is_empty());
7586                         assert_eq!(update_fail_htlcs.len(), 1);
7587                         assert!(update_fail_malformed_htlcs.is_empty());
7588                         assert!(update_fee.is_none());
7589                         (update_fail_htlcs[0].clone(), commitment_signed)
7590                 },
7591                 _ => panic!("Unexpected event"),
7592         };
7593         check_added_monitors!(nodes[1], 1);
7594
7595         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7596         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7597
7598         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7599         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7600         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7601         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7602 }
7603
7604 #[test]
7605 fn test_announce_disable_channels() {
7606         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7607         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7608
7609         let chanmon_cfgs = create_chanmon_cfgs(2);
7610         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7611         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7612         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7613
7614         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7615         create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7616         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7617
7618         // Disconnect peers
7619         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7620         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7621
7622         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7623         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7624         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7625         assert_eq!(msg_events.len(), 3);
7626         let mut chans_disabled = HashMap::new();
7627         for e in msg_events {
7628                 match e {
7629                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7630                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7631                                 // Check that each channel gets updated exactly once
7632                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7633                                         panic!("Generated ChannelUpdate for wrong chan!");
7634                                 }
7635                         },
7636                         _ => panic!("Unexpected event"),
7637                 }
7638         }
7639         // Reconnect peers
7640         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7641         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7642         assert_eq!(reestablish_1.len(), 3);
7643         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7644         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7645         assert_eq!(reestablish_2.len(), 3);
7646
7647         // Reestablish chan_1
7648         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7649         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7650         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7651         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7652         // Reestablish chan_2
7653         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7654         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7655         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7656         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7657         // Reestablish chan_3
7658         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7659         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7660         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7661         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7662
7663         nodes[0].node.timer_tick_occurred();
7664         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7665         nodes[0].node.timer_tick_occurred();
7666         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7667         assert_eq!(msg_events.len(), 3);
7668         for e in msg_events {
7669                 match e {
7670                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7671                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7672                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7673                                         // Each update should have a higher timestamp than the previous one, replacing
7674                                         // the old one.
7675                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7676                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7677                                 }
7678                         },
7679                         _ => panic!("Unexpected event"),
7680                 }
7681         }
7682         // Check that each channel gets updated exactly once
7683         assert!(chans_disabled.is_empty());
7684 }
7685
7686 #[test]
7687 fn test_bump_penalty_txn_on_revoked_commitment() {
7688         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7689         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7690
7691         let chanmon_cfgs = create_chanmon_cfgs(2);
7692         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7693         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7694         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7695
7696         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7697
7698         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7699         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7700                 .with_features(InvoiceFeatures::known());
7701         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7702         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7703
7704         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7705         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7706         assert_eq!(revoked_txn[0].output.len(), 4);
7707         assert_eq!(revoked_txn[0].input.len(), 1);
7708         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7709         let revoked_txid = revoked_txn[0].txid();
7710
7711         let mut penalty_sum = 0;
7712         for outp in revoked_txn[0].output.iter() {
7713                 if outp.script_pubkey.is_v0_p2wsh() {
7714                         penalty_sum += outp.value;
7715                 }
7716         }
7717
7718         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7719         let header_114 = connect_blocks(&nodes[1], 14);
7720
7721         // Actually revoke tx by claiming a HTLC
7722         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7723         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7724         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7725         check_added_monitors!(nodes[1], 1);
7726
7727         // One or more justice tx should have been broadcast, check it
7728         let penalty_1;
7729         let feerate_1;
7730         {
7731                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7732                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7733                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7734                 assert_eq!(node_txn[0].output.len(), 1);
7735                 check_spends!(node_txn[0], revoked_txn[0]);
7736                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7737                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7738                 penalty_1 = node_txn[0].txid();
7739                 node_txn.clear();
7740         };
7741
7742         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7743         connect_blocks(&nodes[1], 15);
7744         let mut penalty_2 = penalty_1;
7745         let mut feerate_2 = 0;
7746         {
7747                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7748                 assert_eq!(node_txn.len(), 1);
7749                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7750                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7751                         assert_eq!(node_txn[0].output.len(), 1);
7752                         check_spends!(node_txn[0], revoked_txn[0]);
7753                         penalty_2 = node_txn[0].txid();
7754                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7755                         assert_ne!(penalty_2, penalty_1);
7756                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7757                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7758                         // Verify 25% bump heuristic
7759                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7760                         node_txn.clear();
7761                 }
7762         }
7763         assert_ne!(feerate_2, 0);
7764
7765         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7766         connect_blocks(&nodes[1], 1);
7767         let penalty_3;
7768         let mut feerate_3 = 0;
7769         {
7770                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7771                 assert_eq!(node_txn.len(), 1);
7772                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7773                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7774                         assert_eq!(node_txn[0].output.len(), 1);
7775                         check_spends!(node_txn[0], revoked_txn[0]);
7776                         penalty_3 = node_txn[0].txid();
7777                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7778                         assert_ne!(penalty_3, penalty_2);
7779                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7780                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7781                         // Verify 25% bump heuristic
7782                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7783                         node_txn.clear();
7784                 }
7785         }
7786         assert_ne!(feerate_3, 0);
7787
7788         nodes[1].node.get_and_clear_pending_events();
7789         nodes[1].node.get_and_clear_pending_msg_events();
7790 }
7791
7792 #[test]
7793 fn test_bump_penalty_txn_on_revoked_htlcs() {
7794         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7795         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7796
7797         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7798         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7799         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7800         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7801         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7802
7803         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7804         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7805         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7806         let scorer = test_utils::TestScorer::with_penalty(0);
7807         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7808         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7809                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7810         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7811         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7812         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7813                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7814         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7815
7816         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7817         assert_eq!(revoked_local_txn[0].input.len(), 1);
7818         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7819
7820         // Revoke local commitment tx
7821         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7822
7823         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7824         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7825         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7826         check_closed_broadcast!(nodes[1], true);
7827         check_added_monitors!(nodes[1], 1);
7828         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7829         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7830
7831         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7832         assert_eq!(revoked_htlc_txn.len(), 3);
7833         check_spends!(revoked_htlc_txn[1], chan.3);
7834
7835         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7836         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7837         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7838
7839         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7840         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7841         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7842         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7843
7844         // Broadcast set of revoked txn on A
7845         let hash_128 = connect_blocks(&nodes[0], 40);
7846         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7847         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7848         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7849         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7850         let events = nodes[0].node.get_and_clear_pending_events();
7851         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7852         match events[1] {
7853                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7854                 _ => panic!("Unexpected event"),
7855         }
7856         let first;
7857         let feerate_1;
7858         let penalty_txn;
7859         {
7860                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7861                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7862                 // Verify claim tx are spending revoked HTLC txn
7863
7864                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7865                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7866                 // which are included in the same block (they are broadcasted because we scan the
7867                 // transactions linearly and generate claims as we go, they likely should be removed in the
7868                 // future).
7869                 assert_eq!(node_txn[0].input.len(), 1);
7870                 check_spends!(node_txn[0], revoked_local_txn[0]);
7871                 assert_eq!(node_txn[1].input.len(), 1);
7872                 check_spends!(node_txn[1], revoked_local_txn[0]);
7873                 assert_eq!(node_txn[2].input.len(), 1);
7874                 check_spends!(node_txn[2], revoked_local_txn[0]);
7875
7876                 // Each of the three justice transactions claim a separate (single) output of the three
7877                 // available, which we check here:
7878                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7879                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7880                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7881
7882                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7883                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7884
7885                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7886                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7887                 // a remote commitment tx has already been confirmed).
7888                 check_spends!(node_txn[3], chan.3);
7889
7890                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7891                 // output, checked above).
7892                 assert_eq!(node_txn[4].input.len(), 2);
7893                 assert_eq!(node_txn[4].output.len(), 1);
7894                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7895
7896                 first = node_txn[4].txid();
7897                 // Store both feerates for later comparison
7898                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7899                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7900                 penalty_txn = vec![node_txn[2].clone()];
7901                 node_txn.clear();
7902         }
7903
7904         // Connect one more block to see if bumped penalty are issued for HTLC txn
7905         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7906         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7907         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7908         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7909         {
7910                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7911                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7912
7913                 check_spends!(node_txn[0], revoked_local_txn[0]);
7914                 check_spends!(node_txn[1], revoked_local_txn[0]);
7915                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7916                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7917                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7918                 } else {
7919                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7920                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7921                 }
7922
7923                 node_txn.clear();
7924         };
7925
7926         // Few more blocks to confirm penalty txn
7927         connect_blocks(&nodes[0], 4);
7928         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7929         let header_144 = connect_blocks(&nodes[0], 9);
7930         let node_txn = {
7931                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7932                 assert_eq!(node_txn.len(), 1);
7933
7934                 assert_eq!(node_txn[0].input.len(), 2);
7935                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7936                 // Verify bumped tx is different and 25% bump heuristic
7937                 assert_ne!(first, node_txn[0].txid());
7938                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7939                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7940                 assert!(feerate_2 * 100 > feerate_1 * 125);
7941                 let txn = vec![node_txn[0].clone()];
7942                 node_txn.clear();
7943                 txn
7944         };
7945         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7946         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7947         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7948         connect_blocks(&nodes[0], 20);
7949         {
7950                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7951                 // We verify than no new transaction has been broadcast because previously
7952                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7953                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7954                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7955                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7956                 // up bumped justice generation.
7957                 assert_eq!(node_txn.len(), 0);
7958                 node_txn.clear();
7959         }
7960         check_closed_broadcast!(nodes[0], true);
7961         check_added_monitors!(nodes[0], 1);
7962 }
7963
7964 #[test]
7965 fn test_bump_penalty_txn_on_remote_commitment() {
7966         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7967         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7968
7969         // Create 2 HTLCs
7970         // Provide preimage for one
7971         // Check aggregation
7972
7973         let chanmon_cfgs = create_chanmon_cfgs(2);
7974         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7975         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7976         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7977
7978         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7979         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7980         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7981
7982         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7983         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7984         assert_eq!(remote_txn[0].output.len(), 4);
7985         assert_eq!(remote_txn[0].input.len(), 1);
7986         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7987
7988         // Claim a HTLC without revocation (provide B monitor with preimage)
7989         nodes[1].node.claim_funds(payment_preimage);
7990         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7991         mine_transaction(&nodes[1], &remote_txn[0]);
7992         check_added_monitors!(nodes[1], 2);
7993         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7994
7995         // One or more claim tx should have been broadcast, check it
7996         let timeout;
7997         let preimage;
7998         let preimage_bump;
7999         let feerate_timeout;
8000         let feerate_preimage;
8001         {
8002                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8003                 // 9 transactions including:
8004                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8005                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8006                 // 2 * HTLC-Success (one RBF bump we'll check later)
8007                 // 1 * HTLC-Timeout
8008                 assert_eq!(node_txn.len(), 8);
8009                 assert_eq!(node_txn[0].input.len(), 1);
8010                 assert_eq!(node_txn[6].input.len(), 1);
8011                 check_spends!(node_txn[0], remote_txn[0]);
8012                 check_spends!(node_txn[6], remote_txn[0]);
8013
8014                 check_spends!(node_txn[1], chan.3);
8015                 check_spends!(node_txn[2], node_txn[1]);
8016
8017                 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
8018                         preimage_bump = node_txn[3].clone();
8019                         check_spends!(node_txn[3], remote_txn[0]);
8020
8021                         assert_eq!(node_txn[1], node_txn[4]);
8022                         assert_eq!(node_txn[2], node_txn[5]);
8023                 } else {
8024                         preimage_bump = node_txn[7].clone();
8025                         check_spends!(node_txn[7], remote_txn[0]);
8026                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8027
8028                         assert_eq!(node_txn[1], node_txn[3]);
8029                         assert_eq!(node_txn[2], node_txn[4]);
8030                 }
8031
8032                 timeout = node_txn[6].txid();
8033                 let index = node_txn[6].input[0].previous_output.vout;
8034                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8035                 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8036
8037                 preimage = node_txn[0].txid();
8038                 let index = node_txn[0].input[0].previous_output.vout;
8039                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8040                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8041
8042                 node_txn.clear();
8043         };
8044         assert_ne!(feerate_timeout, 0);
8045         assert_ne!(feerate_preimage, 0);
8046
8047         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8048         connect_blocks(&nodes[1], 15);
8049         {
8050                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8051                 assert_eq!(node_txn.len(), 1);
8052                 assert_eq!(node_txn[0].input.len(), 1);
8053                 assert_eq!(preimage_bump.input.len(), 1);
8054                 check_spends!(node_txn[0], remote_txn[0]);
8055                 check_spends!(preimage_bump, remote_txn[0]);
8056
8057                 let index = preimage_bump.input[0].previous_output.vout;
8058                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8059                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8060                 assert!(new_feerate * 100 > feerate_timeout * 125);
8061                 assert_ne!(timeout, preimage_bump.txid());
8062
8063                 let index = node_txn[0].input[0].previous_output.vout;
8064                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8065                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8066                 assert!(new_feerate * 100 > feerate_preimage * 125);
8067                 assert_ne!(preimage, node_txn[0].txid());
8068
8069                 node_txn.clear();
8070         }
8071
8072         nodes[1].node.get_and_clear_pending_events();
8073         nodes[1].node.get_and_clear_pending_msg_events();
8074 }
8075
8076 #[test]
8077 fn test_counterparty_raa_skip_no_crash() {
8078         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8079         // commitment transaction, we would have happily carried on and provided them the next
8080         // commitment transaction based on one RAA forward. This would probably eventually have led to
8081         // channel closure, but it would not have resulted in funds loss. Still, our
8082         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8083         // check simply that the channel is closed in response to such an RAA, but don't check whether
8084         // we decide to punish our counterparty for revoking their funds (as we don't currently
8085         // implement that).
8086         let chanmon_cfgs = create_chanmon_cfgs(2);
8087         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8088         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8089         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8090         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8091
8092         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8093         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8094
8095         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8096
8097         // Make signer believe we got a counterparty signature, so that it allows the revocation
8098         keys.get_enforcement_state().last_holder_commitment -= 1;
8099         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8100
8101         // Must revoke without gaps
8102         keys.get_enforcement_state().last_holder_commitment -= 1;
8103         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8104
8105         keys.get_enforcement_state().last_holder_commitment -= 1;
8106         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8107                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8108
8109         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8110                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8111         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8112         check_added_monitors!(nodes[1], 1);
8113         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8114 }
8115
8116 #[test]
8117 fn test_bump_txn_sanitize_tracking_maps() {
8118         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8119         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8120
8121         let chanmon_cfgs = create_chanmon_cfgs(2);
8122         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8123         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8124         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8125
8126         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8127         // Lock HTLC in both directions
8128         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8129         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8130
8131         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8132         assert_eq!(revoked_local_txn[0].input.len(), 1);
8133         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8134
8135         // Revoke local commitment tx
8136         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8137
8138         // Broadcast set of revoked txn on A
8139         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8140         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8141         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8142
8143         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8144         check_closed_broadcast!(nodes[0], true);
8145         check_added_monitors!(nodes[0], 1);
8146         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8147         let penalty_txn = {
8148                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8149                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8150                 check_spends!(node_txn[0], revoked_local_txn[0]);
8151                 check_spends!(node_txn[1], revoked_local_txn[0]);
8152                 check_spends!(node_txn[2], revoked_local_txn[0]);
8153                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8154                 node_txn.clear();
8155                 penalty_txn
8156         };
8157         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8158         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8159         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8160         {
8161                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8162                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8163                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8164         }
8165 }
8166
8167 #[test]
8168 fn test_pending_claimed_htlc_no_balance_underflow() {
8169         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8170         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8171         let chanmon_cfgs = create_chanmon_cfgs(2);
8172         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8173         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8174         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8175         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8176
8177         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8178         nodes[1].node.claim_funds(payment_preimage);
8179         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8180         check_added_monitors!(nodes[1], 1);
8181         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8182
8183         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8184         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8185         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8186         check_added_monitors!(nodes[0], 1);
8187         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8188
8189         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8190         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8191         // can get our balance.
8192
8193         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8194         // the public key of the only hop. This works around ChannelDetails not showing the
8195         // almost-claimed HTLC as available balance.
8196         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8197         route.payment_params = None; // This is all wrong, but unnecessary
8198         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8199         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8200         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8201
8202         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8203 }
8204
8205 #[test]
8206 fn test_channel_conf_timeout() {
8207         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8208         // confirm within 2016 blocks, as recommended by BOLT 2.
8209         let chanmon_cfgs = create_chanmon_cfgs(2);
8210         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8211         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8212         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8213
8214         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8215
8216         // The outbound node should wait forever for confirmation:
8217         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8218         // copied here instead of directly referencing the constant.
8219         connect_blocks(&nodes[0], 2016);
8220         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8221
8222         // The inbound node should fail the channel after exactly 2016 blocks
8223         connect_blocks(&nodes[1], 2015);
8224         check_added_monitors!(nodes[1], 0);
8225         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8226
8227         connect_blocks(&nodes[1], 1);
8228         check_added_monitors!(nodes[1], 1);
8229         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8230         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8231         assert_eq!(close_ev.len(), 1);
8232         match close_ev[0] {
8233                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8234                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8235                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8236                 },
8237                 _ => panic!("Unexpected event"),
8238         }
8239 }
8240
8241 #[test]
8242 fn test_override_channel_config() {
8243         let chanmon_cfgs = create_chanmon_cfgs(2);
8244         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8245         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8246         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8247
8248         // Node0 initiates a channel to node1 using the override config.
8249         let mut override_config = UserConfig::default();
8250         override_config.own_channel_config.our_to_self_delay = 200;
8251
8252         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8253
8254         // Assert the channel created by node0 is using the override config.
8255         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8256         assert_eq!(res.channel_flags, 0);
8257         assert_eq!(res.to_self_delay, 200);
8258 }
8259
8260 #[test]
8261 fn test_override_0msat_htlc_minimum() {
8262         let mut zero_config = UserConfig::default();
8263         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8264         let chanmon_cfgs = create_chanmon_cfgs(2);
8265         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8266         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8267         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8268
8269         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8270         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8271         assert_eq!(res.htlc_minimum_msat, 1);
8272
8273         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8274         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8275         assert_eq!(res.htlc_minimum_msat, 1);
8276 }
8277
8278 #[test]
8279 fn test_channel_update_has_correct_htlc_maximum_msat() {
8280         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8281         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8282         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8283         // 90% of the `channel_value`.
8284         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8285
8286         let mut config_30_percent = UserConfig::default();
8287         config_30_percent.own_channel_config.announced_channel = true;
8288         config_30_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8289         let mut config_50_percent = UserConfig::default();
8290         config_50_percent.own_channel_config.announced_channel = true;
8291         config_50_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8292         let mut config_95_percent = UserConfig::default();
8293         config_95_percent.own_channel_config.announced_channel = true;
8294         config_95_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8295         let mut config_100_percent = UserConfig::default();
8296         config_100_percent.own_channel_config.announced_channel = true;
8297         config_100_percent.own_channel_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8298
8299         let chanmon_cfgs = create_chanmon_cfgs(4);
8300         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8301         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)]);
8302         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8303
8304         let channel_value_satoshis = 100000;
8305         let channel_value_msat = channel_value_satoshis * 1000;
8306         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8307         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8308         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8309
8310         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());
8311         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());
8312
8313         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8314         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8315         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8316         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8317         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8318         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8319
8320         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8321         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8322         // `channel_value`.
8323         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8324         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8325         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8326         // `channel_value`.
8327         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8328 }
8329
8330 #[test]
8331 fn test_manually_accept_inbound_channel_request() {
8332         let mut manually_accept_conf = UserConfig::default();
8333         manually_accept_conf.manually_accept_inbound_channels = true;
8334         let chanmon_cfgs = create_chanmon_cfgs(2);
8335         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8336         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8337         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8338
8339         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8340         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8341
8342         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8343
8344         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8345         // accepting the inbound channel request.
8346         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8347
8348         let events = nodes[1].node.get_and_clear_pending_events();
8349         match events[0] {
8350                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8351                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8352                 }
8353                 _ => panic!("Unexpected event"),
8354         }
8355
8356         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8357         assert_eq!(accept_msg_ev.len(), 1);
8358
8359         match accept_msg_ev[0] {
8360                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8361                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8362                 }
8363                 _ => panic!("Unexpected event"),
8364         }
8365
8366         nodes[1].node.force_close_channel(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8367
8368         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8369         assert_eq!(close_msg_ev.len(), 1);
8370
8371         let events = nodes[1].node.get_and_clear_pending_events();
8372         match events[0] {
8373                 Event::ChannelClosed { user_channel_id, .. } => {
8374                         assert_eq!(user_channel_id, 23);
8375                 }
8376                 _ => panic!("Unexpected event"),
8377         }
8378 }
8379
8380 #[test]
8381 fn test_manually_reject_inbound_channel_request() {
8382         let mut manually_accept_conf = UserConfig::default();
8383         manually_accept_conf.manually_accept_inbound_channels = true;
8384         let chanmon_cfgs = create_chanmon_cfgs(2);
8385         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8386         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8387         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8388
8389         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8390         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8391
8392         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8393
8394         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8395         // rejecting the inbound channel request.
8396         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8397
8398         let events = nodes[1].node.get_and_clear_pending_events();
8399         match events[0] {
8400                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8401                         nodes[1].node.force_close_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8402                 }
8403                 _ => panic!("Unexpected event"),
8404         }
8405
8406         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8407         assert_eq!(close_msg_ev.len(), 1);
8408
8409         match close_msg_ev[0] {
8410                 MessageSendEvent::HandleError { ref node_id, .. } => {
8411                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8412                 }
8413                 _ => panic!("Unexpected event"),
8414         }
8415         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8416 }
8417
8418 #[test]
8419 fn test_reject_funding_before_inbound_channel_accepted() {
8420         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8421         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8422         // the node operator before the counterparty sends a `FundingCreated` message. If a
8423         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8424         // and the channel should be closed.
8425         let mut manually_accept_conf = UserConfig::default();
8426         manually_accept_conf.manually_accept_inbound_channels = true;
8427         let chanmon_cfgs = create_chanmon_cfgs(2);
8428         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8429         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8430         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8431
8432         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8433         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8434         let temp_channel_id = res.temporary_channel_id;
8435
8436         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8437
8438         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8439         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8440
8441         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8442         nodes[1].node.get_and_clear_pending_events();
8443
8444         // Get the `AcceptChannel` message of `nodes[1]` without calling
8445         // `ChannelManager::accept_inbound_channel`, which generates a
8446         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8447         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8448         // succeed when `nodes[0]` is passed to it.
8449         {
8450                 let mut lock;
8451                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8452                 let accept_chan_msg = channel.get_accept_channel_message();
8453                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8454         }
8455
8456         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8457
8458         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8459         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8460
8461         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8462         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8463
8464         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8465         assert_eq!(close_msg_ev.len(), 1);
8466
8467         let expected_err = "FundingCreated message received before the channel was accepted";
8468         match close_msg_ev[0] {
8469                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8470                         assert_eq!(msg.channel_id, temp_channel_id);
8471                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8472                         assert_eq!(msg.data, expected_err);
8473                 }
8474                 _ => panic!("Unexpected event"),
8475         }
8476
8477         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8478 }
8479
8480 #[test]
8481 fn test_can_not_accept_inbound_channel_twice() {
8482         let mut manually_accept_conf = UserConfig::default();
8483         manually_accept_conf.manually_accept_inbound_channels = true;
8484         let chanmon_cfgs = create_chanmon_cfgs(2);
8485         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8486         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8487         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8488
8489         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8490         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8491
8492         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8493
8494         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8495         // accepting the inbound channel request.
8496         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8497
8498         let events = nodes[1].node.get_and_clear_pending_events();
8499         match events[0] {
8500                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8501                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8502                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8503                         match api_res {
8504                                 Err(APIError::APIMisuseError { err }) => {
8505                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8506                                 },
8507                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8508                                 Err(_) => panic!("Unexpected Error"),
8509                         }
8510                 }
8511                 _ => panic!("Unexpected event"),
8512         }
8513
8514         // Ensure that the channel wasn't closed after attempting to accept it twice.
8515         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8516         assert_eq!(accept_msg_ev.len(), 1);
8517
8518         match accept_msg_ev[0] {
8519                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8520                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8521                 }
8522                 _ => panic!("Unexpected event"),
8523         }
8524 }
8525
8526 #[test]
8527 fn test_can_not_accept_unknown_inbound_channel() {
8528         let chanmon_cfg = create_chanmon_cfgs(2);
8529         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8530         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8531         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8532
8533         let unknown_channel_id = [0; 32];
8534         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8535         match api_res {
8536                 Err(APIError::ChannelUnavailable { err }) => {
8537                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8538                 },
8539                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8540                 Err(_) => panic!("Unexpected Error"),
8541         }
8542 }
8543
8544 #[test]
8545 fn test_simple_mpp() {
8546         // Simple test of sending a multi-path payment.
8547         let chanmon_cfgs = create_chanmon_cfgs(4);
8548         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8549         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8550         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8551
8552         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8553         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8554         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8555         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8556
8557         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8558         let path = route.paths[0].clone();
8559         route.paths.push(path);
8560         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8561         route.paths[0][0].short_channel_id = chan_1_id;
8562         route.paths[0][1].short_channel_id = chan_3_id;
8563         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8564         route.paths[1][0].short_channel_id = chan_2_id;
8565         route.paths[1][1].short_channel_id = chan_4_id;
8566         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8567         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8568 }
8569
8570 #[test]
8571 fn test_preimage_storage() {
8572         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8573         let chanmon_cfgs = create_chanmon_cfgs(2);
8574         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8575         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8576         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8577
8578         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8579
8580         {
8581                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8582                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8583                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8584                 check_added_monitors!(nodes[0], 1);
8585                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8586                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8587                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8588                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8589         }
8590         // Note that after leaving the above scope we have no knowledge of any arguments or return
8591         // values from previous calls.
8592         expect_pending_htlcs_forwardable!(nodes[1]);
8593         let events = nodes[1].node.get_and_clear_pending_events();
8594         assert_eq!(events.len(), 1);
8595         match events[0] {
8596                 Event::PaymentReceived { ref purpose, .. } => {
8597                         match &purpose {
8598                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8599                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8600                                 },
8601                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8602                         }
8603                 },
8604                 _ => panic!("Unexpected event"),
8605         }
8606 }
8607
8608 #[test]
8609 #[allow(deprecated)]
8610 fn test_secret_timeout() {
8611         // Simple test of payment secret storage time outs. After
8612         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8613         let chanmon_cfgs = create_chanmon_cfgs(2);
8614         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8615         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8616         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8617
8618         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8619
8620         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8621
8622         // We should fail to register the same payment hash twice, at least until we've connected a
8623         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8624         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8625                 assert_eq!(err, "Duplicate payment hash");
8626         } else { panic!(); }
8627         let mut block = {
8628                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8629                 Block {
8630                         header: BlockHeader {
8631                                 version: 0x2000000,
8632                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8633                                 merkle_root: Default::default(),
8634                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8635                         txdata: vec![],
8636                 }
8637         };
8638         connect_block(&nodes[1], &block);
8639         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8640                 assert_eq!(err, "Duplicate payment hash");
8641         } else { panic!(); }
8642
8643         // If we then connect the second block, we should be able to register the same payment hash
8644         // again (this time getting a new payment secret).
8645         block.header.prev_blockhash = block.header.block_hash();
8646         block.header.time += 1;
8647         connect_block(&nodes[1], &block);
8648         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8649         assert_ne!(payment_secret_1, our_payment_secret);
8650
8651         {
8652                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8653                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8654                 check_added_monitors!(nodes[0], 1);
8655                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8656                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8657                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8658                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8659         }
8660         // Note that after leaving the above scope we have no knowledge of any arguments or return
8661         // values from previous calls.
8662         expect_pending_htlcs_forwardable!(nodes[1]);
8663         let events = nodes[1].node.get_and_clear_pending_events();
8664         assert_eq!(events.len(), 1);
8665         match events[0] {
8666                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8667                         assert!(payment_preimage.is_none());
8668                         assert_eq!(payment_secret, our_payment_secret);
8669                         // We don't actually have the payment preimage with which to claim this payment!
8670                 },
8671                 _ => panic!("Unexpected event"),
8672         }
8673 }
8674
8675 #[test]
8676 fn test_bad_secret_hash() {
8677         // Simple test of unregistered payment hash/invalid payment secret handling
8678         let chanmon_cfgs = create_chanmon_cfgs(2);
8679         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8680         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8681         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8682
8683         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8684
8685         let random_payment_hash = PaymentHash([42; 32]);
8686         let random_payment_secret = PaymentSecret([43; 32]);
8687         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8688         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8689
8690         // All the below cases should end up being handled exactly identically, so we macro the
8691         // resulting events.
8692         macro_rules! handle_unknown_invalid_payment_data {
8693                 () => {
8694                         check_added_monitors!(nodes[0], 1);
8695                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8696                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8697                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8698                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8699
8700                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8701                         // again to process the pending backwards-failure of the HTLC
8702                         expect_pending_htlcs_forwardable!(nodes[1]);
8703                         expect_pending_htlcs_forwardable!(nodes[1]);
8704                         check_added_monitors!(nodes[1], 1);
8705
8706                         // We should fail the payment back
8707                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8708                         match events.pop().unwrap() {
8709                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8710                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8711                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8712                                 },
8713                                 _ => panic!("Unexpected event"),
8714                         }
8715                 }
8716         }
8717
8718         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8719         // Error data is the HTLC value (100,000) and current block height
8720         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8721
8722         // Send a payment with the right payment hash but the wrong payment secret
8723         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8724         handle_unknown_invalid_payment_data!();
8725         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8726
8727         // Send a payment with a random payment hash, but the right payment secret
8728         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8729         handle_unknown_invalid_payment_data!();
8730         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8731
8732         // Send a payment with a random payment hash and random payment secret
8733         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8734         handle_unknown_invalid_payment_data!();
8735         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8736 }
8737
8738 #[test]
8739 fn test_update_err_monitor_lockdown() {
8740         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8741         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8742         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8743         //
8744         // This scenario may happen in a watchtower setup, where watchtower process a block height
8745         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8746         // commitment at same time.
8747
8748         let chanmon_cfgs = create_chanmon_cfgs(2);
8749         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8750         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8751         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8752
8753         // Create some initial channel
8754         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8755         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8756
8757         // Rebalance the network to generate htlc in the two directions
8758         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8759
8760         // Route a HTLC from node 0 to node 1 (but don't settle)
8761         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8762
8763         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8764         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8765         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8766         let persister = test_utils::TestPersister::new();
8767         let watchtower = {
8768                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8769                 let mut w = test_utils::TestVecWriter(Vec::new());
8770                 monitor.write(&mut w).unwrap();
8771                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8772                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8773                 assert!(new_monitor == *monitor);
8774                 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);
8775                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8776                 watchtower
8777         };
8778         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8779         let block = Block { header, txdata: vec![] };
8780         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8781         // transaction lock time requirements here.
8782         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8783         watchtower.chain_monitor.block_connected(&block, 200);
8784
8785         // Try to update ChannelMonitor
8786         nodes[1].node.claim_funds(preimage);
8787         check_added_monitors!(nodes[1], 1);
8788         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8789
8790         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8791         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8792         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8793         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8794                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8795                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8796                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8797                 } else { assert!(false); }
8798         } else { assert!(false); };
8799         // Our local monitor is in-sync and hasn't processed yet timeout
8800         check_added_monitors!(nodes[0], 1);
8801         let events = nodes[0].node.get_and_clear_pending_events();
8802         assert_eq!(events.len(), 1);
8803 }
8804
8805 #[test]
8806 fn test_concurrent_monitor_claim() {
8807         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8808         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8809         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8810         // state N+1 confirms. Alice claims output from state N+1.
8811
8812         let chanmon_cfgs = create_chanmon_cfgs(2);
8813         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8814         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8815         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8816
8817         // Create some initial channel
8818         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8819         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8820
8821         // Rebalance the network to generate htlc in the two directions
8822         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8823
8824         // Route a HTLC from node 0 to node 1 (but don't settle)
8825         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8826
8827         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8828         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8829         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8830         let persister = test_utils::TestPersister::new();
8831         let watchtower_alice = {
8832                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8833                 let mut w = test_utils::TestVecWriter(Vec::new());
8834                 monitor.write(&mut w).unwrap();
8835                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8836                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8837                 assert!(new_monitor == *monitor);
8838                 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);
8839                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8840                 watchtower
8841         };
8842         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8843         let block = Block { header, txdata: vec![] };
8844         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8845         // transaction lock time requirements here.
8846         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));
8847         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8848
8849         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8850         {
8851                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8852                 assert_eq!(txn.len(), 2);
8853                 txn.clear();
8854         }
8855
8856         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8857         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8858         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8859         let persister = test_utils::TestPersister::new();
8860         let watchtower_bob = {
8861                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8862                 let mut w = test_utils::TestVecWriter(Vec::new());
8863                 monitor.write(&mut w).unwrap();
8864                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8865                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8866                 assert!(new_monitor == *monitor);
8867                 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);
8868                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8869                 watchtower
8870         };
8871         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8872         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8873
8874         // Route another payment to generate another update with still previous HTLC pending
8875         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8876         {
8877                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8878         }
8879         check_added_monitors!(nodes[1], 1);
8880
8881         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8882         assert_eq!(updates.update_add_htlcs.len(), 1);
8883         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8884         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8885                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8886                         // Watchtower Alice should already have seen the block and reject the update
8887                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8888                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8889                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8890                 } else { assert!(false); }
8891         } else { assert!(false); };
8892         // Our local monitor is in-sync and hasn't processed yet timeout
8893         check_added_monitors!(nodes[0], 1);
8894
8895         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8896         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8897         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8898
8899         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8900         let bob_state_y;
8901         {
8902                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8903                 assert_eq!(txn.len(), 2);
8904                 bob_state_y = txn[0].clone();
8905                 txn.clear();
8906         };
8907
8908         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8909         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8910         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);
8911         {
8912                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8913                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8914                 // the onchain detection of the HTLC output
8915                 assert_eq!(htlc_txn.len(), 2);
8916                 check_spends!(htlc_txn[0], bob_state_y);
8917                 check_spends!(htlc_txn[1], bob_state_y);
8918         }
8919 }
8920
8921 #[test]
8922 fn test_pre_lockin_no_chan_closed_update() {
8923         // Test that if a peer closes a channel in response to a funding_created message we don't
8924         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8925         // message).
8926         //
8927         // Doing so would imply a channel monitor update before the initial channel monitor
8928         // registration, violating our API guarantees.
8929         //
8930         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8931         // then opening a second channel with the same funding output as the first (which is not
8932         // rejected because the first channel does not exist in the ChannelManager) and closing it
8933         // before receiving funding_signed.
8934         let chanmon_cfgs = create_chanmon_cfgs(2);
8935         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8936         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8937         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8938
8939         // Create an initial channel
8940         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8941         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8942         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8943         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8944         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8945
8946         // Move the first channel through the funding flow...
8947         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8948
8949         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8950         check_added_monitors!(nodes[0], 0);
8951
8952         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8953         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8954         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8955         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8956         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8957 }
8958
8959 #[test]
8960 fn test_htlc_no_detection() {
8961         // This test is a mutation to underscore the detection logic bug we had
8962         // before #653. HTLC value routed is above the remaining balance, thus
8963         // inverting HTLC and `to_remote` output. HTLC will come second and
8964         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8965         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8966         // outputs order detection for correct spending children filtring.
8967
8968         let chanmon_cfgs = create_chanmon_cfgs(2);
8969         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8970         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8971         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8972
8973         // Create some initial channels
8974         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8975
8976         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8977         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8978         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8979         assert_eq!(local_txn[0].input.len(), 1);
8980         assert_eq!(local_txn[0].output.len(), 3);
8981         check_spends!(local_txn[0], chan_1.3);
8982
8983         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8984         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8985         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8986         // We deliberately connect the local tx twice as this should provoke a failure calling
8987         // this test before #653 fix.
8988         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);
8989         check_closed_broadcast!(nodes[0], true);
8990         check_added_monitors!(nodes[0], 1);
8991         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8992         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8993
8994         let htlc_timeout = {
8995                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8996                 assert_eq!(node_txn[1].input.len(), 1);
8997                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8998                 check_spends!(node_txn[1], local_txn[0]);
8999                 node_txn[1].clone()
9000         };
9001
9002         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9003         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9004         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9005         expect_payment_failed!(nodes[0], our_payment_hash, true);
9006 }
9007
9008 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9009         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9010         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9011         // Carol, Alice would be the upstream node, and Carol the downstream.)
9012         //
9013         // Steps of the test:
9014         // 1) Alice sends a HTLC to Carol through Bob.
9015         // 2) Carol doesn't settle the HTLC.
9016         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9017         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9018         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9019         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9020         // 5) Carol release the preimage to Bob off-chain.
9021         // 6) Bob claims the offered output on the broadcasted commitment.
9022         let chanmon_cfgs = create_chanmon_cfgs(3);
9023         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9024         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9025         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9026
9027         // Create some initial channels
9028         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9029         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9030
9031         // Steps (1) and (2):
9032         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9033         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9034
9035         // Check that Alice's commitment transaction now contains an output for this HTLC.
9036         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9037         check_spends!(alice_txn[0], chan_ab.3);
9038         assert_eq!(alice_txn[0].output.len(), 2);
9039         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9040         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9041         assert_eq!(alice_txn.len(), 2);
9042
9043         // Steps (3) and (4):
9044         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9045         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9046         let mut force_closing_node = 0; // Alice force-closes
9047         let mut counterparty_node = 1; // Bob if Alice force-closes
9048
9049         // Bob force-closes
9050         if !broadcast_alice {
9051                 force_closing_node = 1;
9052                 counterparty_node = 0;
9053         }
9054         nodes[force_closing_node].node.force_close_channel(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9055         check_closed_broadcast!(nodes[force_closing_node], true);
9056         check_added_monitors!(nodes[force_closing_node], 1);
9057         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9058         if go_onchain_before_fulfill {
9059                 let txn_to_broadcast = match broadcast_alice {
9060                         true => alice_txn.clone(),
9061                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9062                 };
9063                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9064                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9065                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9066                 if broadcast_alice {
9067                         check_closed_broadcast!(nodes[1], true);
9068                         check_added_monitors!(nodes[1], 1);
9069                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9070                 }
9071                 assert_eq!(bob_txn.len(), 1);
9072                 check_spends!(bob_txn[0], chan_ab.3);
9073         }
9074
9075         // Step (5):
9076         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9077         // process of removing the HTLC from their commitment transactions.
9078         nodes[2].node.claim_funds(payment_preimage);
9079         check_added_monitors!(nodes[2], 1);
9080         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9081
9082         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9083         assert!(carol_updates.update_add_htlcs.is_empty());
9084         assert!(carol_updates.update_fail_htlcs.is_empty());
9085         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9086         assert!(carol_updates.update_fee.is_none());
9087         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9088
9089         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9090         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9091         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9092         if !go_onchain_before_fulfill && broadcast_alice {
9093                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9094                 assert_eq!(events.len(), 1);
9095                 match events[0] {
9096                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9097                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9098                         },
9099                         _ => panic!("Unexpected event"),
9100                 };
9101         }
9102         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9103         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9104         // Carol<->Bob's updated commitment transaction info.
9105         check_added_monitors!(nodes[1], 2);
9106
9107         let events = nodes[1].node.get_and_clear_pending_msg_events();
9108         assert_eq!(events.len(), 2);
9109         let bob_revocation = match events[0] {
9110                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9111                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9112                         (*msg).clone()
9113                 },
9114                 _ => panic!("Unexpected event"),
9115         };
9116         let bob_updates = match events[1] {
9117                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9118                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9119                         (*updates).clone()
9120                 },
9121                 _ => panic!("Unexpected event"),
9122         };
9123
9124         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9125         check_added_monitors!(nodes[2], 1);
9126         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9127         check_added_monitors!(nodes[2], 1);
9128
9129         let events = nodes[2].node.get_and_clear_pending_msg_events();
9130         assert_eq!(events.len(), 1);
9131         let carol_revocation = match events[0] {
9132                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9133                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9134                         (*msg).clone()
9135                 },
9136                 _ => panic!("Unexpected event"),
9137         };
9138         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9139         check_added_monitors!(nodes[1], 1);
9140
9141         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9142         // here's where we put said channel's commitment tx on-chain.
9143         let mut txn_to_broadcast = alice_txn.clone();
9144         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9145         if !go_onchain_before_fulfill {
9146                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9147                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9148                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9149                 if broadcast_alice {
9150                         check_closed_broadcast!(nodes[1], true);
9151                         check_added_monitors!(nodes[1], 1);
9152                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9153                 }
9154                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9155                 if broadcast_alice {
9156                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9157                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9158                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9159                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9160                         // broadcasted.
9161                         assert_eq!(bob_txn.len(), 3);
9162                         check_spends!(bob_txn[1], chan_ab.3);
9163                 } else {
9164                         assert_eq!(bob_txn.len(), 2);
9165                         check_spends!(bob_txn[0], chan_ab.3);
9166                 }
9167         }
9168
9169         // Step (6):
9170         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9171         // broadcasted commitment transaction.
9172         {
9173                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9174                 if go_onchain_before_fulfill {
9175                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9176                         assert_eq!(bob_txn.len(), 2);
9177                 }
9178                 let script_weight = match broadcast_alice {
9179                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9180                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9181                 };
9182                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9183                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9184                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9185                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9186                 if broadcast_alice && !go_onchain_before_fulfill {
9187                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9188                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9189                 } else {
9190                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9191                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9192                 }
9193         }
9194 }
9195
9196 #[test]
9197 fn test_onchain_htlc_settlement_after_close() {
9198         do_test_onchain_htlc_settlement_after_close(true, true);
9199         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9200         do_test_onchain_htlc_settlement_after_close(true, false);
9201         do_test_onchain_htlc_settlement_after_close(false, false);
9202 }
9203
9204 #[test]
9205 fn test_duplicate_chan_id() {
9206         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9207         // already open we reject it and keep the old channel.
9208         //
9209         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9210         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9211         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9212         // updating logic for the existing channel.
9213         let chanmon_cfgs = create_chanmon_cfgs(2);
9214         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9215         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9216         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9217
9218         // Create an initial channel
9219         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9220         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9221         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9222         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()));
9223
9224         // Try to create a second channel with the same temporary_channel_id as the first and check
9225         // that it is rejected.
9226         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9227         {
9228                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9229                 assert_eq!(events.len(), 1);
9230                 match events[0] {
9231                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9232                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9233                                 // first (valid) and second (invalid) channels are closed, given they both have
9234                                 // the same non-temporary channel_id. However, currently we do not, so we just
9235                                 // move forward with it.
9236                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9237                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9238                         },
9239                         _ => panic!("Unexpected event"),
9240                 }
9241         }
9242
9243         // Move the first channel through the funding flow...
9244         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9245
9246         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9247         check_added_monitors!(nodes[0], 0);
9248
9249         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9250         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9251         {
9252                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9253                 assert_eq!(added_monitors.len(), 1);
9254                 assert_eq!(added_monitors[0].0, funding_output);
9255                 added_monitors.clear();
9256         }
9257         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9258
9259         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9260         let channel_id = funding_outpoint.to_channel_id();
9261
9262         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9263         // temporary one).
9264
9265         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9266         // Technically this is allowed by the spec, but we don't support it and there's little reason
9267         // to. Still, it shouldn't cause any other issues.
9268         open_chan_msg.temporary_channel_id = channel_id;
9269         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9270         {
9271                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9272                 assert_eq!(events.len(), 1);
9273                 match events[0] {
9274                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9275                                 // Technically, at this point, nodes[1] would be justified in thinking both
9276                                 // channels are closed, but currently we do not, so we just move forward with it.
9277                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9278                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9279                         },
9280                         _ => panic!("Unexpected event"),
9281                 }
9282         }
9283
9284         // Now try to create a second channel which has a duplicate funding output.
9285         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9286         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9287         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9288         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()));
9289         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9290
9291         let funding_created = {
9292                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9293                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9294                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9295                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9296                 // channelmanager in a possibly nonsense state instead).
9297                 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9298                 let logger = test_utils::TestLogger::new();
9299                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9300         };
9301         check_added_monitors!(nodes[0], 0);
9302         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9303         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9304         // still needs to be cleared here.
9305         check_added_monitors!(nodes[1], 1);
9306
9307         // ...still, nodes[1] will reject the duplicate channel.
9308         {
9309                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9310                 assert_eq!(events.len(), 1);
9311                 match events[0] {
9312                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9313                                 // Technically, at this point, nodes[1] would be justified in thinking both
9314                                 // channels are closed, but currently we do not, so we just move forward with it.
9315                                 assert_eq!(msg.channel_id, channel_id);
9316                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9317                         },
9318                         _ => panic!("Unexpected event"),
9319                 }
9320         }
9321
9322         // finally, finish creating the original channel and send a payment over it to make sure
9323         // everything is functional.
9324         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9325         {
9326                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9327                 assert_eq!(added_monitors.len(), 1);
9328                 assert_eq!(added_monitors[0].0, funding_output);
9329                 added_monitors.clear();
9330         }
9331
9332         let events_4 = nodes[0].node.get_and_clear_pending_events();
9333         assert_eq!(events_4.len(), 0);
9334         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9335         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9336
9337         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9338         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9339         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9340         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9341 }
9342
9343 #[test]
9344 fn test_error_chans_closed() {
9345         // Test that we properly handle error messages, closing appropriate channels.
9346         //
9347         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9348         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9349         // we can test various edge cases around it to ensure we don't regress.
9350         let chanmon_cfgs = create_chanmon_cfgs(3);
9351         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9352         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9353         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9354
9355         // Create some initial channels
9356         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9357         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9358         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9359
9360         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9361         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9362         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9363
9364         // Closing a channel from a different peer has no effect
9365         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9366         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9367
9368         // Closing one channel doesn't impact others
9369         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9370         check_added_monitors!(nodes[0], 1);
9371         check_closed_broadcast!(nodes[0], false);
9372         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9373         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9374         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9375         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);
9376         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);
9377
9378         // A null channel ID should close all channels
9379         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9380         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9381         check_added_monitors!(nodes[0], 2);
9382         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9383         let events = nodes[0].node.get_and_clear_pending_msg_events();
9384         assert_eq!(events.len(), 2);
9385         match events[0] {
9386                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9387                         assert_eq!(msg.contents.flags & 2, 2);
9388                 },
9389                 _ => panic!("Unexpected event"),
9390         }
9391         match events[1] {
9392                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9393                         assert_eq!(msg.contents.flags & 2, 2);
9394                 },
9395                 _ => panic!("Unexpected event"),
9396         }
9397         // Note that at this point users of a standard PeerHandler will end up calling
9398         // peer_disconnected with no_connection_possible set to false, duplicating the
9399         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9400         // users with their own peer handling logic. We duplicate the call here, however.
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         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9405         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9406         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9407 }
9408
9409 #[test]
9410 fn test_invalid_funding_tx() {
9411         // Test that we properly handle invalid funding transactions sent to us from a peer.
9412         //
9413         // Previously, all other major lightning implementations had failed to properly sanitize
9414         // funding transactions from their counterparties, leading to a multi-implementation critical
9415         // security vulnerability (though we always sanitized properly, we've previously had
9416         // un-released crashes in the sanitization process).
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         for output in tx.output.iter_mut() {
9428                 // Make the confirmed funding transaction have a bogus script_pubkey
9429                 output.script_pubkey = bitcoin::Script::new();
9430         }
9431
9432         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9433         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()));
9434         check_added_monitors!(nodes[1], 1);
9435
9436         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()));
9437         check_added_monitors!(nodes[0], 1);
9438
9439         let events_1 = nodes[0].node.get_and_clear_pending_events();
9440         assert_eq!(events_1.len(), 0);
9441
9442         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9443         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9444         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9445
9446         let expected_err = "funding tx had wrong script/value or output index";
9447         confirm_transaction_at(&nodes[1], &tx, 1);
9448         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9449         check_added_monitors!(nodes[1], 1);
9450         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9451         assert_eq!(events_2.len(), 1);
9452         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9453                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9454                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9455                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9456                 } else { panic!(); }
9457         } else { panic!(); }
9458         assert_eq!(nodes[1].node.list_channels().len(), 0);
9459 }
9460
9461 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9462         // In the first version of the chain::Confirm interface, after a refactor was made to not
9463         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9464         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9465         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9466         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9467         // spending transaction until height N+1 (or greater). This was due to the way
9468         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9469         // spending transaction at the height the input transaction was confirmed at, not whether we
9470         // should broadcast a spending transaction at the current height.
9471         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9472         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9473         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9474         // until we learned about an additional block.
9475         //
9476         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9477         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9478         let chanmon_cfgs = create_chanmon_cfgs(3);
9479         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9480         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9481         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9482         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9483
9484         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9485         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9486         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9487         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9488         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9489
9490         nodes[1].node.force_close_channel(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9491         check_closed_broadcast!(nodes[1], true);
9492         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9493         check_added_monitors!(nodes[1], 1);
9494         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9495         assert_eq!(node_txn.len(), 1);
9496
9497         let conf_height = nodes[1].best_block_info().1;
9498         if !test_height_before_timelock {
9499                 connect_blocks(&nodes[1], 24 * 6);
9500         }
9501         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9502                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9503         if test_height_before_timelock {
9504                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9505                 // generate any events or broadcast any transactions
9506                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9507                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9508         } else {
9509                 // We should broadcast an HTLC transaction spending our funding transaction first
9510                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9511                 assert_eq!(spending_txn.len(), 2);
9512                 assert_eq!(spending_txn[0], node_txn[0]);
9513                 check_spends!(spending_txn[1], node_txn[0]);
9514                 // We should also generate a SpendableOutputs event with the to_self output (as its
9515                 // timelock is up).
9516                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9517                 assert_eq!(descriptor_spend_txn.len(), 1);
9518
9519                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9520                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9521                 // additional block built on top of the current chain.
9522                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9523                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9524                 expect_pending_htlcs_forwardable!(nodes[1]);
9525                 check_added_monitors!(nodes[1], 1);
9526
9527                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9528                 assert!(updates.update_add_htlcs.is_empty());
9529                 assert!(updates.update_fulfill_htlcs.is_empty());
9530                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9531                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9532                 assert!(updates.update_fee.is_none());
9533                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9534                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9535                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9536         }
9537 }
9538
9539 #[test]
9540 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9541         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9542         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9543 }
9544
9545 #[test]
9546 fn test_forwardable_regen() {
9547         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9548         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9549         // HTLCs.
9550         // We test it for both payment receipt and payment forwarding.
9551
9552         let chanmon_cfgs = create_chanmon_cfgs(3);
9553         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9554         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9555         let persister: test_utils::TestPersister;
9556         let new_chain_monitor: test_utils::TestChainMonitor;
9557         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9558         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9559         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9560         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9561
9562         // First send a payment to nodes[1]
9563         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9564         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9565         check_added_monitors!(nodes[0], 1);
9566
9567         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9568         assert_eq!(events.len(), 1);
9569         let payment_event = SendEvent::from_event(events.pop().unwrap());
9570         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9571         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9572
9573         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9574
9575         // Next send a payment which is forwarded by nodes[1]
9576         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9577         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9578         check_added_monitors!(nodes[0], 1);
9579
9580         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9581         assert_eq!(events.len(), 1);
9582         let payment_event = SendEvent::from_event(events.pop().unwrap());
9583         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9584         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9585
9586         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9587         // generated
9588         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9589
9590         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9591         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9592         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9593
9594         let nodes_1_serialized = nodes[1].node.encode();
9595         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9596         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9597         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9598         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9599
9600         persister = test_utils::TestPersister::new();
9601         let keys_manager = &chanmon_cfgs[1].keys_manager;
9602         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);
9603         nodes[1].chain_monitor = &new_chain_monitor;
9604
9605         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9606         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9607                 &mut chan_0_monitor_read, keys_manager).unwrap();
9608         assert!(chan_0_monitor_read.is_empty());
9609         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9610         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9611                 &mut chan_1_monitor_read, keys_manager).unwrap();
9612         assert!(chan_1_monitor_read.is_empty());
9613
9614         let mut nodes_1_read = &nodes_1_serialized[..];
9615         let (_, nodes_1_deserialized_tmp) = {
9616                 let mut channel_monitors = HashMap::new();
9617                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9618                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9619                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9620                         default_config: UserConfig::default(),
9621                         keys_manager,
9622                         fee_estimator: node_cfgs[1].fee_estimator,
9623                         chain_monitor: nodes[1].chain_monitor,
9624                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9625                         logger: nodes[1].logger,
9626                         channel_monitors,
9627                 }).unwrap()
9628         };
9629         nodes_1_deserialized = nodes_1_deserialized_tmp;
9630         assert!(nodes_1_read.is_empty());
9631
9632         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9633         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9634         nodes[1].node = &nodes_1_deserialized;
9635         check_added_monitors!(nodes[1], 2);
9636
9637         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9638         // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9639         // the commitment state.
9640         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9641
9642         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9643
9644         expect_pending_htlcs_forwardable!(nodes[1]);
9645         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9646         check_added_monitors!(nodes[1], 1);
9647
9648         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9649         assert_eq!(events.len(), 1);
9650         let payment_event = SendEvent::from_event(events.pop().unwrap());
9651         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9652         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9653         expect_pending_htlcs_forwardable!(nodes[2]);
9654         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9655
9656         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9657         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9658 }
9659
9660 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9661         let chanmon_cfgs = create_chanmon_cfgs(2);
9662         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9663         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9664         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9665
9666         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9667
9668         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9669                 .with_features(InvoiceFeatures::known());
9670         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9671
9672         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9673
9674         {
9675                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9676                 check_added_monitors!(nodes[0], 1);
9677                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9678                 assert_eq!(events.len(), 1);
9679                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9680                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9681                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9682         }
9683         expect_pending_htlcs_forwardable!(nodes[1]);
9684         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9685
9686         {
9687                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9688                 check_added_monitors!(nodes[0], 1);
9689                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9690                 assert_eq!(events.len(), 1);
9691                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9692                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9693                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9694                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9695                 // assume the second is a privacy attack (no longer particularly relevant
9696                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9697                 // the first HTLC delivered above.
9698         }
9699
9700         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9701         nodes[1].node.process_pending_htlc_forwards();
9702
9703         if test_for_second_fail_panic {
9704                 // Now we go fail back the first HTLC from the user end.
9705                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9706
9707                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9708                 nodes[1].node.process_pending_htlc_forwards();
9709
9710                 check_added_monitors!(nodes[1], 1);
9711                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9712                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9713
9714                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9715                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9716                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9717
9718                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9719                 assert_eq!(failure_events.len(), 2);
9720                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9721                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9722         } else {
9723                 // Let the second HTLC fail and claim the first
9724                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9725                 nodes[1].node.process_pending_htlc_forwards();
9726
9727                 check_added_monitors!(nodes[1], 1);
9728                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9729                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9730                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9731
9732                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9733
9734                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9735         }
9736 }
9737
9738 #[test]
9739 fn test_dup_htlc_second_fail_panic() {
9740         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9741         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9742         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9743         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9744         do_test_dup_htlc_second_rejected(true);
9745 }
9746
9747 #[test]
9748 fn test_dup_htlc_second_rejected() {
9749         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9750         // simply reject the second HTLC but are still able to claim the first HTLC.
9751         do_test_dup_htlc_second_rejected(false);
9752 }
9753
9754 #[test]
9755 fn test_inconsistent_mpp_params() {
9756         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9757         // such HTLC and allow the second to stay.
9758         let chanmon_cfgs = create_chanmon_cfgs(4);
9759         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9760         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9761         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9762
9763         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9764         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9765         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9766         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9767
9768         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9769                 .with_features(InvoiceFeatures::known());
9770         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9771         assert_eq!(route.paths.len(), 2);
9772         route.paths.sort_by(|path_a, _| {
9773                 // Sort the path so that the path through nodes[1] comes first
9774                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9775                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9776         });
9777         let payment_params_opt = Some(payment_params);
9778
9779         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9780
9781         let cur_height = nodes[0].best_block_info().1;
9782         let payment_id = PaymentId([42; 32]);
9783         {
9784                 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();
9785                 check_added_monitors!(nodes[0], 1);
9786
9787                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9788                 assert_eq!(events.len(), 1);
9789                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9790         }
9791         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9792
9793         {
9794                 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();
9795                 check_added_monitors!(nodes[0], 1);
9796
9797                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9798                 assert_eq!(events.len(), 1);
9799                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9800
9801                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9802                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9803
9804                 expect_pending_htlcs_forwardable!(nodes[2]);
9805                 check_added_monitors!(nodes[2], 1);
9806
9807                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9808                 assert_eq!(events.len(), 1);
9809                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9810
9811                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9812                 check_added_monitors!(nodes[3], 0);
9813                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9814
9815                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9816                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9817                 // post-payment_secrets) and fail back the new HTLC.
9818         }
9819         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9820         nodes[3].node.process_pending_htlc_forwards();
9821         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9822         nodes[3].node.process_pending_htlc_forwards();
9823
9824         check_added_monitors!(nodes[3], 1);
9825
9826         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9827         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9828         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9829
9830         expect_pending_htlcs_forwardable!(nodes[2]);
9831         check_added_monitors!(nodes[2], 1);
9832
9833         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9834         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9835         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9836
9837         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9838
9839         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();
9840         check_added_monitors!(nodes[0], 1);
9841
9842         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9843         assert_eq!(events.len(), 1);
9844         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9845
9846         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9847 }
9848
9849 #[test]
9850 fn test_keysend_payments_to_public_node() {
9851         let chanmon_cfgs = create_chanmon_cfgs(2);
9852         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9853         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9854         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9855
9856         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9857         let network_graph = nodes[0].network_graph;
9858         let payer_pubkey = nodes[0].node.get_our_node_id();
9859         let payee_pubkey = nodes[1].node.get_our_node_id();
9860         let route_params = RouteParameters {
9861                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9862                 final_value_msat: 10000,
9863                 final_cltv_expiry_delta: 40,
9864         };
9865         let scorer = test_utils::TestScorer::with_penalty(0);
9866         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9867         let route = find_route(&payer_pubkey, &route_params, &network_graph.read_only(), None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9868
9869         let test_preimage = PaymentPreimage([42; 32]);
9870         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9871         check_added_monitors!(nodes[0], 1);
9872         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9873         assert_eq!(events.len(), 1);
9874         let event = events.pop().unwrap();
9875         let path = vec![&nodes[1]];
9876         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9877         claim_payment(&nodes[0], &path, test_preimage);
9878 }
9879
9880 #[test]
9881 fn test_keysend_payments_to_private_node() {
9882         let chanmon_cfgs = create_chanmon_cfgs(2);
9883         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9884         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9885         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9886
9887         let payer_pubkey = nodes[0].node.get_our_node_id();
9888         let payee_pubkey = nodes[1].node.get_our_node_id();
9889         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9890         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9891
9892         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9893         let route_params = RouteParameters {
9894                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9895                 final_value_msat: 10000,
9896                 final_cltv_expiry_delta: 40,
9897         };
9898         let network_graph = nodes[0].network_graph;
9899         let first_hops = nodes[0].node.list_usable_channels();
9900         let scorer = test_utils::TestScorer::with_penalty(0);
9901         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9902         let route = find_route(
9903                 &payer_pubkey, &route_params, &network_graph.read_only(),
9904                 Some(&first_hops.iter().collect::<Vec<_>>()), nodes[0].logger, &scorer, &random_seed_bytes
9905         ).unwrap();
9906
9907         let test_preimage = PaymentPreimage([42; 32]);
9908         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9909         check_added_monitors!(nodes[0], 1);
9910         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9911         assert_eq!(events.len(), 1);
9912         let event = events.pop().unwrap();
9913         let path = vec![&nodes[1]];
9914         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9915         claim_payment(&nodes[0], &path, test_preimage);
9916 }
9917
9918 #[test]
9919 fn test_double_partial_claim() {
9920         // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9921         // time out, the sender resends only some of the MPP parts, then the user processes the
9922         // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9923         // amount.
9924         let chanmon_cfgs = create_chanmon_cfgs(4);
9925         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9926         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9927         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9928
9929         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9930         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9931         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9932         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9933
9934         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9935         assert_eq!(route.paths.len(), 2);
9936         route.paths.sort_by(|path_a, _| {
9937                 // Sort the path so that the path through nodes[1] comes first
9938                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9939                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9940         });
9941
9942         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9943         // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
9944         // amount of time to respond to.
9945
9946         // Connect some blocks to time out the payment
9947         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9948         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9949
9950         expect_pending_htlcs_forwardable!(nodes[3]);
9951
9952         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9953
9954         // nodes[1] now retries one of the two paths...
9955         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9956         check_added_monitors!(nodes[0], 2);
9957
9958         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9959         assert_eq!(events.len(), 2);
9960         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
9961
9962         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9963         // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
9964         nodes[3].node.claim_funds(payment_preimage);
9965         check_added_monitors!(nodes[3], 0);
9966         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9967 }
9968
9969 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
9970         // Test what happens if a node receives an MPP payment, claims it, but crashes before
9971         // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
9972         // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
9973         // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
9974         // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
9975         // not have the preimage tied to the still-pending HTLC.
9976         //
9977         // To get to the correct state, on startup we should propagate the preimage to the
9978         // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
9979         // receiving the preimage without a state update.
9980         //
9981         // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
9982         // definitely claimed.
9983         let chanmon_cfgs = create_chanmon_cfgs(4);
9984         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9985         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9986
9987         let persister: test_utils::TestPersister;
9988         let new_chain_monitor: test_utils::TestChainMonitor;
9989         let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9990
9991         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9992
9993         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9994         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9995         let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
9996         let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
9997
9998         // Create an MPP route for 15k sats, more than the default htlc-max of 10%
9999         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10000         assert_eq!(route.paths.len(), 2);
10001         route.paths.sort_by(|path_a, _| {
10002                 // Sort the path so that the path through nodes[1] comes first
10003                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10004                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10005         });
10006
10007         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10008         check_added_monitors!(nodes[0], 2);
10009
10010         // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10011         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10012         assert_eq!(send_events.len(), 2);
10013         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);
10014         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);
10015
10016         // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10017         // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10018         let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10019         if !persist_both_monitors {
10020                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10021                         if outpoint.to_channel_id() == chan_id_not_persisted {
10022                                 assert!(original_monitor.0.is_empty());
10023                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10024                         }
10025                 }
10026         }
10027
10028         let mut original_manager = test_utils::TestVecWriter(Vec::new());
10029         nodes[3].node.write(&mut original_manager).unwrap();
10030
10031         expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10032
10033         nodes[3].node.claim_funds(payment_preimage);
10034         check_added_monitors!(nodes[3], 2);
10035         expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10036
10037         // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10038         // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10039         // with the old ChannelManager.
10040         let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10041         for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10042                 if outpoint.to_channel_id() == chan_id_persisted {
10043                         assert!(updated_monitor.0.is_empty());
10044                         nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10045                 }
10046         }
10047         // If `persist_both_monitors` is set, get the second monitor here as well
10048         if persist_both_monitors {
10049                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10050                         if outpoint.to_channel_id() == chan_id_not_persisted {
10051                                 assert!(original_monitor.0.is_empty());
10052                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10053                         }
10054                 }
10055         }
10056
10057         // Now restart nodes[3].
10058         persister = test_utils::TestPersister::new();
10059         let keys_manager = &chanmon_cfgs[3].keys_manager;
10060         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);
10061         nodes[3].chain_monitor = &new_chain_monitor;
10062         let mut monitors = Vec::new();
10063         for mut monitor_data in [original_monitor, updated_monitor].iter() {
10064                 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10065                 monitors.push(deserialized_monitor);
10066         }
10067
10068         let config = UserConfig::default();
10069         nodes_3_deserialized = {
10070                 let mut channel_monitors = HashMap::new();
10071                 for monitor in monitors.iter_mut() {
10072                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10073                 }
10074                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10075                         default_config: config,
10076                         keys_manager,
10077                         fee_estimator: node_cfgs[3].fee_estimator,
10078                         chain_monitor: nodes[3].chain_monitor,
10079                         tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10080                         logger: nodes[3].logger,
10081                         channel_monitors,
10082                 }).unwrap().1
10083         };
10084         nodes[3].node = &nodes_3_deserialized;
10085
10086         for monitor in monitors {
10087                 // On startup the preimage should have been copied into the non-persisted monitor:
10088                 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10089                 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10090         }
10091         check_added_monitors!(nodes[3], 2);
10092
10093         nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10094         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10095
10096         // During deserialization, we should have closed one channel and broadcast its latest
10097         // commitment transaction. We should also still have the original PaymentReceived event we
10098         // never finished processing.
10099         let events = nodes[3].node.get_and_clear_pending_events();
10100         assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10101         if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10102         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10103         if persist_both_monitors {
10104                 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10105         }
10106
10107         // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10108         // ChannelManager prior to handling the original one.
10109         if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10110                 events[if persist_both_monitors { 3 } else { 2 }]
10111         {
10112                 assert_eq!(payment_hash, our_payment_hash);
10113         } else { panic!(); }
10114
10115         assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10116         if !persist_both_monitors {
10117                 // If one of the two channels is still live, reveal the payment preimage over it.
10118
10119                 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10120                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10121                 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10122                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10123
10124                 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10125                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10126                 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10127
10128                 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10129
10130                 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10131                 // claim should fly.
10132                 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10133                 check_added_monitors!(nodes[3], 1);
10134                 assert_eq!(ds_msgs.len(), 2);
10135                 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10136
10137                 let cs_updates = match ds_msgs[0] {
10138                         MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10139                                 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10140                                 check_added_monitors!(nodes[2], 1);
10141                                 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10142                                 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10143                                 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10144                                 cs_updates
10145                         }
10146                         _ => panic!(),
10147                 };
10148
10149                 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10150                 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10151                 expect_payment_sent!(nodes[0], payment_preimage);
10152         }
10153 }
10154
10155 #[test]
10156 fn test_partial_claim_before_restart() {
10157         do_test_partial_claim_before_restart(false);
10158         do_test_partial_claim_before_restart(true);
10159 }
10160
10161 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10162 #[derive(Clone, Copy, PartialEq)]
10163 enum ExposureEvent {
10164         /// Breach occurs at HTLC forwarding (see `send_htlc`)
10165         AtHTLCForward,
10166         /// Breach occurs at HTLC reception (see `update_add_htlc`)
10167         AtHTLCReception,
10168         /// Breach occurs at outbound update_fee (see `send_update_fee`)
10169         AtUpdateFeeOutbound,
10170 }
10171
10172 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10173         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10174         // policy.
10175         //
10176         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10177         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10178         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10179         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10180         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10181         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10182         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10183         // might be available again for HTLC processing once the dust bandwidth has cleared up.
10184
10185         let chanmon_cfgs = create_chanmon_cfgs(2);
10186         let mut config = test_default_channel_config();
10187         config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10188         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10189         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10190         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10191
10192         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10193         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10194         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10195         open_channel.max_accepted_htlcs = 60;
10196         if on_holder_tx {
10197                 open_channel.dust_limit_satoshis = 546;
10198         }
10199         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10200         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10201         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10202
10203         let opt_anchors = false;
10204
10205         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10206
10207         if on_holder_tx {
10208                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10209                         chan.holder_dust_limit_satoshis = 546;
10210                 }
10211         }
10212
10213         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10214         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()));
10215         check_added_monitors!(nodes[1], 1);
10216
10217         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()));
10218         check_added_monitors!(nodes[0], 1);
10219
10220         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10221         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10222         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10223
10224         let dust_buffer_feerate = {
10225                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10226                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10227                 chan.get_dust_buffer_feerate(None) as u64
10228         };
10229         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;
10230         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10231
10232         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;
10233         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10234
10235         let dust_htlc_on_counterparty_tx: u64 = 25;
10236         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10237
10238         if on_holder_tx {
10239                 if dust_outbound_balance {
10240                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10241                         // Outbound dust balance: 4372 sats
10242                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10243                         for i in 0..dust_outbound_htlc_on_holder_tx {
10244                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10245                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10246                         }
10247                 } else {
10248                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10249                         // Inbound dust balance: 4372 sats
10250                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10251                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10252                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10253                         }
10254                 }
10255         } else {
10256                 if dust_outbound_balance {
10257                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10258                         // Outbound dust balance: 5000 sats
10259                         for i in 0..dust_htlc_on_counterparty_tx {
10260                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10261                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10262                         }
10263                 } else {
10264                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10265                         // Inbound dust balance: 5000 sats
10266                         for _ in 0..dust_htlc_on_counterparty_tx {
10267                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10268                         }
10269                 }
10270         }
10271
10272         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10273         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10274                 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 });
10275                 let mut config = UserConfig::default();
10276                 // With default dust exposure: 5000 sats
10277                 if on_holder_tx {
10278                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10279                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10280                         unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_options.max_dust_htlc_exposure_msat)));
10281                 } else {
10282                         unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_options.max_dust_htlc_exposure_msat)));
10283                 }
10284         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10285                 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 });
10286                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10287                 check_added_monitors!(nodes[1], 1);
10288                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10289                 assert_eq!(events.len(), 1);
10290                 let payment_event = SendEvent::from_event(events.remove(0));
10291                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10292                 // With default dust exposure: 5000 sats
10293                 if on_holder_tx {
10294                         // Outbound dust balance: 6399 sats
10295                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10296                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10297                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_options.max_dust_htlc_exposure_msat), 1);
10298                 } else {
10299                         // Outbound dust balance: 5200 sats
10300                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_options.max_dust_htlc_exposure_msat), 1);
10301                 }
10302         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10303                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10304                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10305                 {
10306                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10307                         *feerate_lock = *feerate_lock * 10;
10308                 }
10309                 nodes[0].node.timer_tick_occurred();
10310                 check_added_monitors!(nodes[0], 1);
10311                 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);
10312         }
10313
10314         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10315         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10316         added_monitors.clear();
10317 }
10318
10319 #[test]
10320 fn test_max_dust_htlc_exposure() {
10321         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10322         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10323         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10324         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10325         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10326         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10327         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10328         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10329         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10330         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10331         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10332         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10333 }