1bf981680baeb9b6f3ddc35ab7e030cacefcb423
[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;
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA};
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::HTLC_SUCCESS_TX_WEIGHT;
26 use routing::network_graph::{NetworkUpdate, RoutingFees};
27 use routing::router::{Payee, Route, RouteHop, RouteHint, RouteHintHop, RouteParameters, find_route, get_route};
28 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
29 use ln::msgs;
30 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, 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::hashes::sha256::Hash as Sha256;
46 use bitcoin::hashes::Hash;
47
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
50
51 use regex;
52
53 use io;
54 use prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use sync::{Arc, Mutex};
58
59 use ln::functional_test_utils::*;
60 use ln::chan_utils::CommitmentTransaction;
61
62 #[test]
63 fn test_insane_channel_opens() {
64         // Stand up a network of 2 nodes
65         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, None]);
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::channel::MAX_FUNDING_SATOSHIS;
100         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
101
102         // Test all mutations that would make the channel open message insane
103         insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_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 funding value \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"Bogus; channel reserve \(\d+\) is less than dust limit \(\d+\)", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
112
113         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 });
114
115         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 });
116
117         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
118
119         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
120 }
121
122 #[test]
123 fn test_async_inbound_update_fee() {
124         let chanmon_cfgs = create_chanmon_cfgs(2);
125         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
126         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
127         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
128         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
129
130         // balancing
131         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
132
133         // A                                        B
134         // update_fee                            ->
135         // send (1) commitment_signed            -.
136         //                                       <- update_add_htlc/commitment_signed
137         // send (2) RAA (awaiting remote revoke) -.
138         // (1) commitment_signed is delivered    ->
139         //                                       .- send (3) RAA (awaiting remote revoke)
140         // (2) RAA is delivered                  ->
141         //                                       .- send (4) commitment_signed
142         //                                       <- (3) RAA is delivered
143         // send (5) commitment_signed            -.
144         //                                       <- (4) commitment_signed is delivered
145         // send (6) RAA                          -.
146         // (5) commitment_signed is delivered    ->
147         //                                       <- RAA
148         // (6) RAA is delivered                  ->
149
150         // First nodes[0] generates an update_fee
151         {
152                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
153                 *feerate_lock += 20;
154         }
155         nodes[0].node.timer_tick_occurred();
156         check_added_monitors!(nodes[0], 1);
157
158         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
159         assert_eq!(events_0.len(), 1);
160         let (update_msg, commitment_signed) = match events_0[0] { // (1)
161                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
162                         (update_fee.as_ref(), commitment_signed)
163                 },
164                 _ => panic!("Unexpected event"),
165         };
166
167         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
168
169         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
170         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
171         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
172         check_added_monitors!(nodes[1], 1);
173
174         let payment_event = {
175                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
176                 assert_eq!(events_1.len(), 1);
177                 SendEvent::from_event(events_1.remove(0))
178         };
179         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
180         assert_eq!(payment_event.msgs.len(), 1);
181
182         // ...now when the messages get delivered everyone should be happy
183         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
184         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
185         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
186         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
187         check_added_monitors!(nodes[0], 1);
188
189         // deliver(1), generate (3):
190         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
191         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
192         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
193         check_added_monitors!(nodes[1], 1);
194
195         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
196         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
197         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
198         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
199         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
200         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
201         assert!(bs_update.update_fee.is_none()); // (4)
202         check_added_monitors!(nodes[1], 1);
203
204         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
205         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
206         assert!(as_update.update_add_htlcs.is_empty()); // (5)
207         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
208         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
209         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
210         assert!(as_update.update_fee.is_none()); // (5)
211         check_added_monitors!(nodes[0], 1);
212
213         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
214         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
215         // only (6) so get_event_msg's assert(len == 1) passes
216         check_added_monitors!(nodes[0], 1);
217
218         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
219         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
220         check_added_monitors!(nodes[1], 1);
221
222         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
223         check_added_monitors!(nodes[0], 1);
224
225         let events_2 = nodes[0].node.get_and_clear_pending_events();
226         assert_eq!(events_2.len(), 1);
227         match events_2[0] {
228                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
229                 _ => panic!("Unexpected event"),
230         }
231
232         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
233         check_added_monitors!(nodes[1], 1);
234 }
235
236 #[test]
237 fn test_update_fee_unordered_raa() {
238         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
239         // crash in an earlier version of the update_fee patch)
240         let chanmon_cfgs = create_chanmon_cfgs(2);
241         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
242         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
243         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
244         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
245
246         // balancing
247         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
248
249         // First nodes[0] generates an update_fee
250         {
251                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
252                 *feerate_lock += 20;
253         }
254         nodes[0].node.timer_tick_occurred();
255         check_added_monitors!(nodes[0], 1);
256
257         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
258         assert_eq!(events_0.len(), 1);
259         let update_msg = match events_0[0] { // (1)
260                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
261                         update_fee.as_ref()
262                 },
263                 _ => panic!("Unexpected event"),
264         };
265
266         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
267
268         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
269         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
270         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
271         check_added_monitors!(nodes[1], 1);
272
273         let payment_event = {
274                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
275                 assert_eq!(events_1.len(), 1);
276                 SendEvent::from_event(events_1.remove(0))
277         };
278         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
279         assert_eq!(payment_event.msgs.len(), 1);
280
281         // ...now when the messages get delivered everyone should be happy
282         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
283         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
284         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
285         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
286         check_added_monitors!(nodes[0], 1);
287
288         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
289         check_added_monitors!(nodes[1], 1);
290
291         // We can't continue, sadly, because our (1) now has a bogus signature
292 }
293
294 #[test]
295 fn test_multi_flight_update_fee() {
296         let chanmon_cfgs = create_chanmon_cfgs(2);
297         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
298         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
299         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
300         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
301
302         // A                                        B
303         // update_fee/commitment_signed          ->
304         //                                       .- send (1) RAA and (2) commitment_signed
305         // update_fee (never committed)          ->
306         // (3) update_fee                        ->
307         // We have to manually generate the above update_fee, it is allowed by the protocol but we
308         // don't track which updates correspond to which revoke_and_ack responses so we're in
309         // AwaitingRAA mode and will not generate the update_fee yet.
310         //                                       <- (1) RAA delivered
311         // (3) is generated and send (4) CS      -.
312         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
313         // know the per_commitment_point to use for it.
314         //                                       <- (2) commitment_signed delivered
315         // revoke_and_ack                        ->
316         //                                          B should send no response here
317         // (4) commitment_signed delivered       ->
318         //                                       <- RAA/commitment_signed delivered
319         // revoke_and_ack                        ->
320
321         // First nodes[0] generates an update_fee
322         let initial_feerate;
323         {
324                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
325                 initial_feerate = *feerate_lock;
326                 *feerate_lock = initial_feerate + 20;
327         }
328         nodes[0].node.timer_tick_occurred();
329         check_added_monitors!(nodes[0], 1);
330
331         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
332         assert_eq!(events_0.len(), 1);
333         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
334                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
335                         (update_fee.as_ref().unwrap(), commitment_signed)
336                 },
337                 _ => panic!("Unexpected event"),
338         };
339
340         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
341         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
342         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
343         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
344         check_added_monitors!(nodes[1], 1);
345
346         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
347         // transaction:
348         {
349                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
350                 *feerate_lock = initial_feerate + 40;
351         }
352         nodes[0].node.timer_tick_occurred();
353         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
354         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
355
356         // Create the (3) update_fee message that nodes[0] will generate before it does...
357         let mut update_msg_2 = msgs::UpdateFee {
358                 channel_id: update_msg_1.channel_id.clone(),
359                 feerate_per_kw: (initial_feerate + 30) as u32,
360         };
361
362         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
363
364         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
365         // Deliver (3)
366         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
367
368         // Deliver (1), generating (3) and (4)
369         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
370         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
371         check_added_monitors!(nodes[0], 1);
372         assert!(as_second_update.update_add_htlcs.is_empty());
373         assert!(as_second_update.update_fulfill_htlcs.is_empty());
374         assert!(as_second_update.update_fail_htlcs.is_empty());
375         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
376         // Check that the update_fee newly generated matches what we delivered:
377         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
378         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
379
380         // Deliver (2) commitment_signed
381         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
382         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
383         check_added_monitors!(nodes[0], 1);
384         // No commitment_signed so get_event_msg's assert(len == 1) passes
385
386         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
387         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
388         check_added_monitors!(nodes[1], 1);
389
390         // Delever (4)
391         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
392         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
393         check_added_monitors!(nodes[1], 1);
394
395         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
396         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
397         check_added_monitors!(nodes[0], 1);
398
399         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
400         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
401         // No commitment_signed so get_event_msg's assert(len == 1) passes
402         check_added_monitors!(nodes[0], 1);
403
404         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
405         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
406         check_added_monitors!(nodes[1], 1);
407 }
408
409 fn do_test_1_conf_open(connect_style: ConnectStyle) {
410         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
411         // tests that we properly send one in that case.
412         let mut alice_config = UserConfig::default();
413         alice_config.own_channel_config.minimum_depth = 1;
414         alice_config.channel_options.announced_channel = true;
415         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
416         let mut bob_config = UserConfig::default();
417         bob_config.own_channel_config.minimum_depth = 1;
418         bob_config.channel_options.announced_channel = true;
419         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
420         let chanmon_cfgs = create_chanmon_cfgs(2);
421         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
422         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
423         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
424         *nodes[0].connect_style.borrow_mut() = connect_style;
425
426         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
427         mine_transaction(&nodes[1], &tx);
428         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
429
430         mine_transaction(&nodes[0], &tx);
431         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
432         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
433
434         for node in nodes {
435                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
436                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
437                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
438         }
439 }
440 #[test]
441 fn test_1_conf_open() {
442         do_test_1_conf_open(ConnectStyle::BestBlockFirst);
443         do_test_1_conf_open(ConnectStyle::TransactionsFirst);
444         do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
445 }
446
447 fn do_test_sanity_on_in_flight_opens(steps: u8) {
448         // Previously, we had issues deserializing channels when we hadn't connected the first block
449         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
450         // serialization round-trips and simply do steps towards opening a channel and then drop the
451         // Node objects.
452
453         let chanmon_cfgs = create_chanmon_cfgs(2);
454         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
455         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
456         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
457
458         if steps & 0b1000_0000 != 0{
459                 let block = Block {
460                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
461                         txdata: vec![],
462                 };
463                 connect_block(&nodes[0], &block);
464                 connect_block(&nodes[1], &block);
465         }
466
467         if steps & 0x0f == 0 { return; }
468         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
469         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
470
471         if steps & 0x0f == 1 { return; }
472         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
473         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
474
475         if steps & 0x0f == 2 { return; }
476         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
477
478         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
479
480         if steps & 0x0f == 3 { return; }
481         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
482         check_added_monitors!(nodes[0], 0);
483         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
484
485         if steps & 0x0f == 4 { return; }
486         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
487         {
488                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
489                 assert_eq!(added_monitors.len(), 1);
490                 assert_eq!(added_monitors[0].0, funding_output);
491                 added_monitors.clear();
492         }
493         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
494
495         if steps & 0x0f == 5 { return; }
496         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
497         {
498                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
499                 assert_eq!(added_monitors.len(), 1);
500                 assert_eq!(added_monitors[0].0, funding_output);
501                 added_monitors.clear();
502         }
503
504         let events_4 = nodes[0].node.get_and_clear_pending_events();
505         assert_eq!(events_4.len(), 0);
506
507         if steps & 0x0f == 6 { return; }
508         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
509
510         if steps & 0x0f == 7 { return; }
511         confirm_transaction_at(&nodes[0], &tx, 2);
512         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
513         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
514 }
515
516 #[test]
517 fn test_sanity_on_in_flight_opens() {
518         do_test_sanity_on_in_flight_opens(0);
519         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
520         do_test_sanity_on_in_flight_opens(1);
521         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
522         do_test_sanity_on_in_flight_opens(2);
523         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
524         do_test_sanity_on_in_flight_opens(3);
525         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
526         do_test_sanity_on_in_flight_opens(4);
527         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
528         do_test_sanity_on_in_flight_opens(5);
529         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
530         do_test_sanity_on_in_flight_opens(6);
531         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
532         do_test_sanity_on_in_flight_opens(7);
533         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
534         do_test_sanity_on_in_flight_opens(8);
535         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
536 }
537
538 #[test]
539 fn test_update_fee_vanilla() {
540         let chanmon_cfgs = create_chanmon_cfgs(2);
541         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
542         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
543         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
544         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
545
546         {
547                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
548                 *feerate_lock += 25;
549         }
550         nodes[0].node.timer_tick_occurred();
551         check_added_monitors!(nodes[0], 1);
552
553         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
554         assert_eq!(events_0.len(), 1);
555         let (update_msg, commitment_signed) = match events_0[0] {
556                         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 } } => {
557                         (update_fee.as_ref(), commitment_signed)
558                 },
559                 _ => panic!("Unexpected event"),
560         };
561         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
562
563         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
564         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
565         check_added_monitors!(nodes[1], 1);
566
567         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
568         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
569         check_added_monitors!(nodes[0], 1);
570
571         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
572         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
573         // No commitment_signed so get_event_msg's assert(len == 1) passes
574         check_added_monitors!(nodes[0], 1);
575
576         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
577         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
578         check_added_monitors!(nodes[1], 1);
579 }
580
581 #[test]
582 fn test_update_fee_that_funder_cannot_afford() {
583         let chanmon_cfgs = create_chanmon_cfgs(2);
584         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
585         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
586         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
587         let channel_value = 1888;
588         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
589         let channel_id = chan.2;
590
591         let feerate = 260;
592         {
593                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
594                 *feerate_lock = feerate;
595         }
596         nodes[0].node.timer_tick_occurred();
597         check_added_monitors!(nodes[0], 1);
598         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
599
600         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
601
602         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
603
604         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
605         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
606         {
607                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
608
609                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
610                 let num_htlcs = commitment_tx.output.len() - 2;
611                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
612                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
613                 actual_fee = channel_value - actual_fee;
614                 assert_eq!(total_fee, actual_fee);
615         }
616
617         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
618         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
619         {
620                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
621                 *feerate_lock = feerate + 2;
622         }
623         nodes[0].node.timer_tick_occurred();
624         check_added_monitors!(nodes[0], 1);
625
626         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
627
628         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
629
630         //While producing the commitment_signed response after handling a received update_fee request the
631         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
632         //Should produce and error.
633         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
634         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
635         check_added_monitors!(nodes[1], 1);
636         check_closed_broadcast!(nodes[1], true);
637         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
638 }
639
640 #[test]
641 fn test_update_fee_with_fundee_update_add_htlc() {
642         let chanmon_cfgs = create_chanmon_cfgs(2);
643         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
644         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
645         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
646         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
647
648         // balancing
649         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
650
651         {
652                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
653                 *feerate_lock += 20;
654         }
655         nodes[0].node.timer_tick_occurred();
656         check_added_monitors!(nodes[0], 1);
657
658         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
659         assert_eq!(events_0.len(), 1);
660         let (update_msg, commitment_signed) = match events_0[0] {
661                         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 } } => {
662                         (update_fee.as_ref(), commitment_signed)
663                 },
664                 _ => panic!("Unexpected event"),
665         };
666         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
667         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
668         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
669         check_added_monitors!(nodes[1], 1);
670
671         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
672
673         // nothing happens since node[1] is in AwaitingRemoteRevoke
674         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
675         {
676                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
677                 assert_eq!(added_monitors.len(), 0);
678                 added_monitors.clear();
679         }
680         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
681         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
682         // node[1] has nothing to do
683
684         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
685         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
686         check_added_monitors!(nodes[0], 1);
687
688         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
689         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
690         // No commitment_signed so get_event_msg's assert(len == 1) passes
691         check_added_monitors!(nodes[0], 1);
692         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
693         check_added_monitors!(nodes[1], 1);
694         // AwaitingRemoteRevoke ends here
695
696         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
697         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
698         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
699         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
700         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
701         assert_eq!(commitment_update.update_fee.is_none(), true);
702
703         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
704         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
705         check_added_monitors!(nodes[0], 1);
706         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
707
708         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
709         check_added_monitors!(nodes[1], 1);
710         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
711
712         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
713         check_added_monitors!(nodes[1], 1);
714         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
715         // No commitment_signed so get_event_msg's assert(len == 1) passes
716
717         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
718         check_added_monitors!(nodes[0], 1);
719         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
720
721         expect_pending_htlcs_forwardable!(nodes[0]);
722
723         let events = nodes[0].node.get_and_clear_pending_events();
724         assert_eq!(events.len(), 1);
725         match events[0] {
726                 Event::PaymentReceived { .. } => { },
727                 _ => panic!("Unexpected event"),
728         };
729
730         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
731
732         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
733         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
734         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
735         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
736         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
737 }
738
739 #[test]
740 fn test_update_fee() {
741         let chanmon_cfgs = create_chanmon_cfgs(2);
742         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
743         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
744         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
745         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
746         let channel_id = chan.2;
747
748         // A                                        B
749         // (1) update_fee/commitment_signed      ->
750         //                                       <- (2) revoke_and_ack
751         //                                       .- send (3) commitment_signed
752         // (4) update_fee/commitment_signed      ->
753         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
754         //                                       <- (3) commitment_signed delivered
755         // send (6) revoke_and_ack               -.
756         //                                       <- (5) deliver revoke_and_ack
757         // (6) deliver revoke_and_ack            ->
758         //                                       .- send (7) commitment_signed in response to (4)
759         //                                       <- (7) deliver commitment_signed
760         // revoke_and_ack                        ->
761
762         // Create and deliver (1)...
763         let feerate;
764         {
765                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
766                 feerate = *feerate_lock;
767                 *feerate_lock = feerate + 20;
768         }
769         nodes[0].node.timer_tick_occurred();
770         check_added_monitors!(nodes[0], 1);
771
772         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
773         assert_eq!(events_0.len(), 1);
774         let (update_msg, commitment_signed) = match events_0[0] {
775                         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 } } => {
776                         (update_fee.as_ref(), commitment_signed)
777                 },
778                 _ => panic!("Unexpected event"),
779         };
780         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
781
782         // Generate (2) and (3):
783         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
784         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
785         check_added_monitors!(nodes[1], 1);
786
787         // Deliver (2):
788         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
789         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
790         check_added_monitors!(nodes[0], 1);
791
792         // Create and deliver (4)...
793         {
794                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
795                 *feerate_lock = feerate + 30;
796         }
797         nodes[0].node.timer_tick_occurred();
798         check_added_monitors!(nodes[0], 1);
799         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
800         assert_eq!(events_0.len(), 1);
801         let (update_msg, commitment_signed) = match events_0[0] {
802                         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 } } => {
803                         (update_fee.as_ref(), commitment_signed)
804                 },
805                 _ => panic!("Unexpected event"),
806         };
807
808         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
809         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
810         check_added_monitors!(nodes[1], 1);
811         // ... creating (5)
812         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
813         // No commitment_signed so get_event_msg's assert(len == 1) passes
814
815         // Handle (3), creating (6):
816         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
817         check_added_monitors!(nodes[0], 1);
818         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
819         // No commitment_signed so get_event_msg's assert(len == 1) passes
820
821         // Deliver (5):
822         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
823         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
824         check_added_monitors!(nodes[0], 1);
825
826         // Deliver (6), creating (7):
827         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
828         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
829         assert!(commitment_update.update_add_htlcs.is_empty());
830         assert!(commitment_update.update_fulfill_htlcs.is_empty());
831         assert!(commitment_update.update_fail_htlcs.is_empty());
832         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
833         assert!(commitment_update.update_fee.is_none());
834         check_added_monitors!(nodes[1], 1);
835
836         // Deliver (7)
837         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
838         check_added_monitors!(nodes[0], 1);
839         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
840         // No commitment_signed so get_event_msg's assert(len == 1) passes
841
842         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
843         check_added_monitors!(nodes[1], 1);
844         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
845
846         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
847         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
848         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
849         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
850         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
851 }
852
853 #[test]
854 fn fake_network_test() {
855         // Simple test which builds a network of ChannelManagers, connects them to each other, and
856         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
857         let chanmon_cfgs = create_chanmon_cfgs(4);
858         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
859         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
860         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
861
862         // Create some initial channels
863         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
864         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
865         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
866
867         // Rebalance the network a bit by relaying one payment through all the channels...
868         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
869         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
870         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
871         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
872
873         // Send some more payments
874         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
875         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
876         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
877
878         // Test failure packets
879         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
880         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
881
882         // Add a new channel that skips 3
883         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
884
885         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
886         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
887         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
888         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
889         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
890         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
891         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
892
893         // Do some rebalance loop payments, simultaneously
894         let mut hops = Vec::with_capacity(3);
895         hops.push(RouteHop {
896                 pubkey: nodes[2].node.get_our_node_id(),
897                 node_features: NodeFeatures::empty(),
898                 short_channel_id: chan_2.0.contents.short_channel_id,
899                 channel_features: ChannelFeatures::empty(),
900                 fee_msat: 0,
901                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
902         });
903         hops.push(RouteHop {
904                 pubkey: nodes[3].node.get_our_node_id(),
905                 node_features: NodeFeatures::empty(),
906                 short_channel_id: chan_3.0.contents.short_channel_id,
907                 channel_features: ChannelFeatures::empty(),
908                 fee_msat: 0,
909                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
910         });
911         hops.push(RouteHop {
912                 pubkey: nodes[1].node.get_our_node_id(),
913                 node_features: NodeFeatures::known(),
914                 short_channel_id: chan_4.0.contents.short_channel_id,
915                 channel_features: ChannelFeatures::known(),
916                 fee_msat: 1000000,
917                 cltv_expiry_delta: TEST_FINAL_CLTV,
918         });
919         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;
920         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;
921         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payee: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
922
923         let mut hops = Vec::with_capacity(3);
924         hops.push(RouteHop {
925                 pubkey: nodes[3].node.get_our_node_id(),
926                 node_features: NodeFeatures::empty(),
927                 short_channel_id: chan_4.0.contents.short_channel_id,
928                 channel_features: ChannelFeatures::empty(),
929                 fee_msat: 0,
930                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
931         });
932         hops.push(RouteHop {
933                 pubkey: nodes[2].node.get_our_node_id(),
934                 node_features: NodeFeatures::empty(),
935                 short_channel_id: chan_3.0.contents.short_channel_id,
936                 channel_features: ChannelFeatures::empty(),
937                 fee_msat: 0,
938                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
939         });
940         hops.push(RouteHop {
941                 pubkey: nodes[1].node.get_our_node_id(),
942                 node_features: NodeFeatures::known(),
943                 short_channel_id: chan_2.0.contents.short_channel_id,
944                 channel_features: ChannelFeatures::known(),
945                 fee_msat: 1000000,
946                 cltv_expiry_delta: TEST_FINAL_CLTV,
947         });
948         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;
949         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;
950         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payee: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
951
952         // Claim the rebalances...
953         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
954         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
955
956         // Add a duplicate new channel from 2 to 4
957         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
958
959         // Send some payments across both channels
960         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
961         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
962         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
963
964
965         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
966         let events = nodes[0].node.get_and_clear_pending_msg_events();
967         assert_eq!(events.len(), 0);
968         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);
969
970         //TODO: Test that routes work again here as we've been notified that the channel is full
971
972         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
973         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
974         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
975
976         // Close down the channels...
977         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
978         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
979         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
980         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
981         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
982         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
983         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
984         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
985         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
986         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
987         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
988         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
989         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
990         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
991         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
992 }
993
994 #[test]
995 fn holding_cell_htlc_counting() {
996         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
997         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
998         // commitment dance rounds.
999         let chanmon_cfgs = create_chanmon_cfgs(3);
1000         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1001         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1002         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1003         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1004         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1005
1006         let mut payments = Vec::new();
1007         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1008                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1009                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1010                 payments.push((payment_preimage, payment_hash));
1011         }
1012         check_added_monitors!(nodes[1], 1);
1013
1014         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1015         assert_eq!(events.len(), 1);
1016         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1017         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1018
1019         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1020         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1021         // another HTLC.
1022         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1023         {
1024                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1025                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1026                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1027                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1028         }
1029
1030         // This should also be true if we try to forward a payment.
1031         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1032         {
1033                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1034                 check_added_monitors!(nodes[0], 1);
1035         }
1036
1037         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1038         assert_eq!(events.len(), 1);
1039         let payment_event = SendEvent::from_event(events.pop().unwrap());
1040         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1041
1042         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1043         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1044         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1045         // fails), the second will process the resulting failure and fail the HTLC backward.
1046         expect_pending_htlcs_forwardable!(nodes[1]);
1047         expect_pending_htlcs_forwardable!(nodes[1]);
1048         check_added_monitors!(nodes[1], 1);
1049
1050         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1051         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1052         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1053
1054         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1055
1056         // Now forward all the pending HTLCs and claim them back
1057         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1058         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1059         check_added_monitors!(nodes[2], 1);
1060
1061         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1062         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1063         check_added_monitors!(nodes[1], 1);
1064         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1065
1066         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1067         check_added_monitors!(nodes[1], 1);
1068         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1069
1070         for ref update in as_updates.update_add_htlcs.iter() {
1071                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1072         }
1073         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1074         check_added_monitors!(nodes[2], 1);
1075         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1076         check_added_monitors!(nodes[2], 1);
1077         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1078
1079         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1080         check_added_monitors!(nodes[1], 1);
1081         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1082         check_added_monitors!(nodes[1], 1);
1083         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1084
1085         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1086         check_added_monitors!(nodes[2], 1);
1087
1088         expect_pending_htlcs_forwardable!(nodes[2]);
1089
1090         let events = nodes[2].node.get_and_clear_pending_events();
1091         assert_eq!(events.len(), payments.len());
1092         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1093                 match event {
1094                         &Event::PaymentReceived { ref payment_hash, .. } => {
1095                                 assert_eq!(*payment_hash, *hash);
1096                         },
1097                         _ => panic!("Unexpected event"),
1098                 };
1099         }
1100
1101         for (preimage, _) in payments.drain(..) {
1102                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1103         }
1104
1105         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1106 }
1107
1108 #[test]
1109 fn duplicate_htlc_test() {
1110         // Test that we accept duplicate payment_hash HTLCs across the network and that
1111         // claiming/failing them are all separate and don't affect each other
1112         let chanmon_cfgs = create_chanmon_cfgs(6);
1113         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1114         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1115         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1116
1117         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1118         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1119         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1120         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1121         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1122         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1123
1124         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1125
1126         *nodes[0].network_payment_count.borrow_mut() -= 1;
1127         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1128
1129         *nodes[0].network_payment_count.borrow_mut() -= 1;
1130         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1131
1132         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1133         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1134         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1135 }
1136
1137 #[test]
1138 fn test_duplicate_htlc_different_direction_onchain() {
1139         // Test that ChannelMonitor doesn't generate 2 preimage txn
1140         // when we have 2 HTLCs with same preimage that go across a node
1141         // in opposite directions, even with the same payment secret.
1142         let chanmon_cfgs = create_chanmon_cfgs(2);
1143         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1144         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1145         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1146
1147         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1148
1149         // balancing
1150         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1151
1152         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1153
1154         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1155         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, 0).unwrap();
1156         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1157
1158         // Provide preimage to node 0 by claiming payment
1159         nodes[0].node.claim_funds(payment_preimage);
1160         check_added_monitors!(nodes[0], 1);
1161
1162         // Broadcast node 1 commitment txn
1163         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1164
1165         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1166         let mut has_both_htlcs = 0; // check htlcs match ones committed
1167         for outp in remote_txn[0].output.iter() {
1168                 if outp.value == 800_000 / 1000 {
1169                         has_both_htlcs += 1;
1170                 } else if outp.value == 900_000 / 1000 {
1171                         has_both_htlcs += 1;
1172                 }
1173         }
1174         assert_eq!(has_both_htlcs, 2);
1175
1176         mine_transaction(&nodes[0], &remote_txn[0]);
1177         check_added_monitors!(nodes[0], 1);
1178         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1179         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1180
1181         // Check we only broadcast 1 timeout tx
1182         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1183         assert_eq!(claim_txn.len(), 8);
1184         assert_eq!(claim_txn[1], claim_txn[4]);
1185         assert_eq!(claim_txn[2], claim_txn[5]);
1186         check_spends!(claim_txn[1], chan_1.3);
1187         check_spends!(claim_txn[2], claim_txn[1]);
1188         check_spends!(claim_txn[7], claim_txn[1]);
1189
1190         assert_eq!(claim_txn[0].input.len(), 1);
1191         assert_eq!(claim_txn[3].input.len(), 1);
1192         assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1193
1194         assert_eq!(claim_txn[0].input.len(), 1);
1195         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1196         check_spends!(claim_txn[0], remote_txn[0]);
1197         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1198         assert_eq!(claim_txn[6].input.len(), 1);
1199         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1200         check_spends!(claim_txn[6], remote_txn[0]);
1201         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1202
1203         let events = nodes[0].node.get_and_clear_pending_msg_events();
1204         assert_eq!(events.len(), 3);
1205         for e in events {
1206                 match e {
1207                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1208                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1209                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1210                                 assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1211                         },
1212                         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, .. } } => {
1213                                 assert!(update_add_htlcs.is_empty());
1214                                 assert!(update_fail_htlcs.is_empty());
1215                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1216                                 assert!(update_fail_malformed_htlcs.is_empty());
1217                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1218                         },
1219                         _ => panic!("Unexpected event"),
1220                 }
1221         }
1222 }
1223
1224 #[test]
1225 fn test_basic_channel_reserve() {
1226         let chanmon_cfgs = create_chanmon_cfgs(2);
1227         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1228         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1229         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1230         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1231
1232         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1233         let channel_reserve = chan_stat.channel_reserve_msat;
1234
1235         // The 2* and +1 are for the fee spike reserve.
1236         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1237         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1238         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1239         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1240         match err {
1241                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1242                         match &fails[0] {
1243                                 &APIError::ChannelUnavailable{ref err} =>
1244                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1245                                 _ => panic!("Unexpected error variant"),
1246                         }
1247                 },
1248                 _ => panic!("Unexpected error variant"),
1249         }
1250         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1251         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);
1252
1253         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1254 }
1255
1256 #[test]
1257 fn test_fee_spike_violation_fails_htlc() {
1258         let chanmon_cfgs = create_chanmon_cfgs(2);
1259         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1260         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1261         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1262         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1263
1264         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1265         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1266         let secp_ctx = Secp256k1::new();
1267         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1268
1269         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1270
1271         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1272         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1273         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1274         let msg = msgs::UpdateAddHTLC {
1275                 channel_id: chan.2,
1276                 htlc_id: 0,
1277                 amount_msat: htlc_msat,
1278                 payment_hash: payment_hash,
1279                 cltv_expiry: htlc_cltv,
1280                 onion_routing_packet: onion_packet,
1281         };
1282
1283         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1284
1285         // Now manually create the commitment_signed message corresponding to the update_add
1286         // nodes[0] just sent. In the code for construction of this message, "local" refers
1287         // to the sender of the message, and "remote" refers to the receiver.
1288
1289         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1290
1291         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1292
1293         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1294         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1295         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1296                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1297                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1298                 let chan_signer = local_chan.get_signer();
1299                 // Make the signer believe we validated another commitment, so we can release the secret
1300                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1301
1302                 let pubkeys = chan_signer.pubkeys();
1303                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1304                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1305                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1306                  chan_signer.pubkeys().funding_pubkey)
1307         };
1308         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1309                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1310                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1311                 let chan_signer = remote_chan.get_signer();
1312                 let pubkeys = chan_signer.pubkeys();
1313                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1314                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1315                  chan_signer.pubkeys().funding_pubkey)
1316         };
1317
1318         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1319         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1320                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1321
1322         // Build the remote commitment transaction so we can sign it, and then later use the
1323         // signature for the commitment_signed message.
1324         let local_chan_balance = 1313;
1325
1326         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1327                 offered: false,
1328                 amount_msat: 3460001,
1329                 cltv_expiry: htlc_cltv,
1330                 payment_hash,
1331                 transaction_output_index: Some(1),
1332         };
1333
1334         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1335
1336         let res = {
1337                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1338                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1339                 let local_chan_signer = local_chan.get_signer();
1340                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1341                         commitment_number,
1342                         95000,
1343                         local_chan_balance,
1344                         false, local_funding, remote_funding,
1345                         commit_tx_keys.clone(),
1346                         feerate_per_kw,
1347                         &mut vec![(accepted_htlc_info, ())],
1348                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1349                 );
1350                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1351         };
1352
1353         let commit_signed_msg = msgs::CommitmentSigned {
1354                 channel_id: chan.2,
1355                 signature: res.0,
1356                 htlc_signatures: res.1
1357         };
1358
1359         // Send the commitment_signed message to the nodes[1].
1360         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1361         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1362
1363         // Send the RAA to nodes[1].
1364         let raa_msg = msgs::RevokeAndACK {
1365                 channel_id: chan.2,
1366                 per_commitment_secret: local_secret,
1367                 next_per_commitment_point: next_local_point
1368         };
1369         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1370
1371         let events = nodes[1].node.get_and_clear_pending_msg_events();
1372         assert_eq!(events.len(), 1);
1373         // Make sure the HTLC failed in the way we expect.
1374         match events[0] {
1375                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1376                         assert_eq!(update_fail_htlcs.len(), 1);
1377                         update_fail_htlcs[0].clone()
1378                 },
1379                 _ => panic!("Unexpected event"),
1380         };
1381         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1382                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1383
1384         check_added_monitors!(nodes[1], 2);
1385 }
1386
1387 #[test]
1388 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1389         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1390         // Set the fee rate for the channel very high, to the point where the fundee
1391         // sending any above-dust amount would result in a channel reserve violation.
1392         // In this test we check that we would be prevented from sending an HTLC in
1393         // this situation.
1394         let feerate_per_kw = 253;
1395         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1396         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1397         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1398         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1399         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1400
1401         let mut push_amt = 100_000_000;
1402         push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
1403         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1404
1405         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1406
1407         // Sending exactly enough to hit the reserve amount should be accepted
1408         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1409
1410         // However one more HTLC should be significantly over the reserve amount and fail.
1411         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1412         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1413                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1414         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1415         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);
1416 }
1417
1418 #[test]
1419 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1420         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1421         // Set the fee rate for the channel very high, to the point where the funder
1422         // receiving 1 update_add_htlc would result in them closing the channel due
1423         // to channel reserve violation. This close could also happen if the fee went
1424         // up a more realistic amount, but many HTLCs were outstanding at the time of
1425         // the update_add_htlc.
1426         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1427         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1428         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1429         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1430         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1431         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1432
1433         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1434         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1435         let secp_ctx = Secp256k1::new();
1436         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1437         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1438         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1439         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &Some(payment_secret), cur_height, &None).unwrap();
1440         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1441         let msg = msgs::UpdateAddHTLC {
1442                 channel_id: chan.2,
1443                 htlc_id: 1,
1444                 amount_msat: htlc_msat + 1,
1445                 payment_hash: payment_hash,
1446                 cltv_expiry: htlc_cltv,
1447                 onion_routing_packet: onion_packet,
1448         };
1449
1450         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1451         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1452         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);
1453         assert_eq!(nodes[0].node.list_channels().len(), 0);
1454         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1455         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1456         check_added_monitors!(nodes[0], 1);
1457         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() });
1458 }
1459
1460 #[test]
1461 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1462         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1463         // calculating our commitment transaction fee (this was previously broken).
1464         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1465         let feerate_per_kw = 253;
1466         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1467         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1468
1469         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1470         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1471         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1472
1473         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1474         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1475         // transaction fee with 0 HTLCs (183 sats)).
1476         let mut push_amt = 100_000_000;
1477         push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT) / 1000 * 1000;
1478         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1479         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1480
1481         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1482                 + feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000 * 1000 - 1;
1483         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1484         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1485         // commitment transaction fee.
1486         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1487
1488         // One more than the dust amt should fail, however.
1489         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1490         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1491                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1492 }
1493
1494 #[test]
1495 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1496         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1497         // calculating our counterparty's commitment transaction fee (this was previously broken).
1498         let chanmon_cfgs = create_chanmon_cfgs(2);
1499         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1500         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1501         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1502         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1503
1504         let payment_amt = 46000; // Dust amount
1505         // In the previous code, these first four payments would succeed.
1506         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1507         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1508         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1509         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1510
1511         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1512         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1513         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1514         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1515         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1516         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1517
1518         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1519         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1520         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1521         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1522 }
1523
1524 #[test]
1525 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1526         let chanmon_cfgs = create_chanmon_cfgs(3);
1527         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1528         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1529         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1530         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1531         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1532
1533         let feemsat = 239;
1534         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1535         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1536         let feerate = get_feerate!(nodes[0], chan.2);
1537
1538         // Add a 2* and +1 for the fee spike reserve.
1539         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1540         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;
1541         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1542
1543         // Add a pending HTLC.
1544         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1545         let payment_event_1 = {
1546                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1547                 check_added_monitors!(nodes[0], 1);
1548
1549                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1550                 assert_eq!(events.len(), 1);
1551                 SendEvent::from_event(events.remove(0))
1552         };
1553         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1554
1555         // Attempt to trigger a channel reserve violation --> payment failure.
1556         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1557         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;
1558         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1559         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1560
1561         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1562         let secp_ctx = Secp256k1::new();
1563         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1564         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1565         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1566         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1567         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1568         let msg = msgs::UpdateAddHTLC {
1569                 channel_id: chan.2,
1570                 htlc_id: 1,
1571                 amount_msat: htlc_msat + 1,
1572                 payment_hash: our_payment_hash_1,
1573                 cltv_expiry: htlc_cltv,
1574                 onion_routing_packet: onion_packet,
1575         };
1576
1577         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1578         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1579         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1580         assert_eq!(nodes[1].node.list_channels().len(), 1);
1581         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1582         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1583         check_added_monitors!(nodes[1], 1);
1584         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1585 }
1586
1587 #[test]
1588 fn test_inbound_outbound_capacity_is_not_zero() {
1589         let chanmon_cfgs = create_chanmon_cfgs(2);
1590         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1591         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1592         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1593         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1594         let channels0 = node_chanmgrs[0].list_channels();
1595         let channels1 = node_chanmgrs[1].list_channels();
1596         assert_eq!(channels0.len(), 1);
1597         assert_eq!(channels1.len(), 1);
1598
1599         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1600         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1601         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1602
1603         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1604         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1605 }
1606
1607 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1608         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1609 }
1610
1611 #[test]
1612 fn test_channel_reserve_holding_cell_htlcs() {
1613         let chanmon_cfgs = create_chanmon_cfgs(3);
1614         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1615         // When this test was written, the default base fee floated based on the HTLC count.
1616         // It is now fixed, so we simply set the fee to the expected value here.
1617         let mut config = test_default_channel_config();
1618         config.channel_options.forwarding_fee_base_msat = 239;
1619         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1620         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1621         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1622         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1623
1624         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1625         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1626
1627         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1628         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1629
1630         macro_rules! expect_forward {
1631                 ($node: expr) => {{
1632                         let mut events = $node.node.get_and_clear_pending_msg_events();
1633                         assert_eq!(events.len(), 1);
1634                         check_added_monitors!($node, 1);
1635                         let payment_event = SendEvent::from_event(events.remove(0));
1636                         payment_event
1637                 }}
1638         }
1639
1640         let feemsat = 239; // set above
1641         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1642         let feerate = get_feerate!(nodes[0], chan_1.2);
1643
1644         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1645
1646         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1647         {
1648                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1649                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1650                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1651                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1652                         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)));
1653                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1654                 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);
1655         }
1656
1657         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1658         // nodes[0]'s wealth
1659         loop {
1660                 let amt_msat = recv_value_0 + total_fee_msat;
1661                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1662                 // Also, ensure that each payment has enough to be over the dust limit to
1663                 // ensure it'll be included in each commit tx fee calculation.
1664                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1665                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1666                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1667                         break;
1668                 }
1669                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1670
1671                 let (stat01_, stat11_, stat12_, stat22_) = (
1672                         get_channel_value_stat!(nodes[0], chan_1.2),
1673                         get_channel_value_stat!(nodes[1], chan_1.2),
1674                         get_channel_value_stat!(nodes[1], chan_2.2),
1675                         get_channel_value_stat!(nodes[2], chan_2.2),
1676                 );
1677
1678                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1679                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1680                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1681                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1682                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1683         }
1684
1685         // adding pending output.
1686         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1687         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1688         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1689         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1690         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1691         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1692         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1693         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1694         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1695         // policy.
1696         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1697         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1698         let amt_msat_1 = recv_value_1 + total_fee_msat;
1699
1700         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);
1701         let payment_event_1 = {
1702                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1703                 check_added_monitors!(nodes[0], 1);
1704
1705                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1706                 assert_eq!(events.len(), 1);
1707                 SendEvent::from_event(events.remove(0))
1708         };
1709         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1710
1711         // channel reserve test with htlc pending output > 0
1712         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1713         {
1714                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1715                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1716                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1717                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1718         }
1719
1720         // split the rest to test holding cell
1721         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1722         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1723         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1724         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1725         {
1726                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1727                 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);
1728         }
1729
1730         // now see if they go through on both sides
1731         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);
1732         // but this will stuck in the holding cell
1733         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1734         check_added_monitors!(nodes[0], 0);
1735         let events = nodes[0].node.get_and_clear_pending_events();
1736         assert_eq!(events.len(), 0);
1737
1738         // test with outbound holding cell amount > 0
1739         {
1740                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1741                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1742                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1743                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1744                 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);
1745         }
1746
1747         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);
1748         // this will also stuck in the holding cell
1749         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1750         check_added_monitors!(nodes[0], 0);
1751         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1752         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1753
1754         // flush the pending htlc
1755         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1756         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1757         check_added_monitors!(nodes[1], 1);
1758
1759         // the pending htlc should be promoted to committed
1760         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1761         check_added_monitors!(nodes[0], 1);
1762         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1763
1764         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1765         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1766         // No commitment_signed so get_event_msg's assert(len == 1) passes
1767         check_added_monitors!(nodes[0], 1);
1768
1769         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1770         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1771         check_added_monitors!(nodes[1], 1);
1772
1773         expect_pending_htlcs_forwardable!(nodes[1]);
1774
1775         let ref payment_event_11 = expect_forward!(nodes[1]);
1776         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1777         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1778
1779         expect_pending_htlcs_forwardable!(nodes[2]);
1780         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1781
1782         // flush the htlcs in the holding cell
1783         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1784         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1785         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1786         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1787         expect_pending_htlcs_forwardable!(nodes[1]);
1788
1789         let ref payment_event_3 = expect_forward!(nodes[1]);
1790         assert_eq!(payment_event_3.msgs.len(), 2);
1791         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1792         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1793
1794         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1795         expect_pending_htlcs_forwardable!(nodes[2]);
1796
1797         let events = nodes[2].node.get_and_clear_pending_events();
1798         assert_eq!(events.len(), 2);
1799         match events[0] {
1800                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1801                         assert_eq!(our_payment_hash_21, *payment_hash);
1802                         assert_eq!(recv_value_21, amt);
1803                         match &purpose {
1804                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1805                                         assert!(payment_preimage.is_none());
1806                                         assert_eq!(our_payment_secret_21, *payment_secret);
1807                                 },
1808                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1809                         }
1810                 },
1811                 _ => panic!("Unexpected event"),
1812         }
1813         match events[1] {
1814                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1815                         assert_eq!(our_payment_hash_22, *payment_hash);
1816                         assert_eq!(recv_value_22, amt);
1817                         match &purpose {
1818                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1819                                         assert!(payment_preimage.is_none());
1820                                         assert_eq!(our_payment_secret_22, *payment_secret);
1821                                 },
1822                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1823                         }
1824                 },
1825                 _ => panic!("Unexpected event"),
1826         }
1827
1828         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1829         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1830         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1831
1832         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
1833         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1834         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1835
1836         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
1837         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);
1838         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1839         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1840         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1841
1842         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1843         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1844 }
1845
1846 #[test]
1847 fn channel_reserve_in_flight_removes() {
1848         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1849         // can send to its counterparty, but due to update ordering, the other side may not yet have
1850         // considered those HTLCs fully removed.
1851         // This tests that we don't count HTLCs which will not be included in the next remote
1852         // commitment transaction towards the reserve value (as it implies no commitment transaction
1853         // will be generated which violates the remote reserve value).
1854         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1855         // To test this we:
1856         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1857         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1858         //    you only consider the value of the first HTLC, it may not),
1859         //  * start routing a third HTLC from A to B,
1860         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1861         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1862         //  * deliver the first fulfill from B
1863         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1864         //    claim,
1865         //  * deliver A's response CS and RAA.
1866         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1867         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
1868         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1869         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1870         let chanmon_cfgs = create_chanmon_cfgs(2);
1871         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1872         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1873         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1874         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1875
1876         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1877         // Route the first two HTLCs.
1878         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1879         let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1880
1881         // Start routing the third HTLC (this is just used to get everyone in the right state).
1882         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
1883         let send_1 = {
1884                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
1885                 check_added_monitors!(nodes[0], 1);
1886                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1887                 assert_eq!(events.len(), 1);
1888                 SendEvent::from_event(events.remove(0))
1889         };
1890
1891         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1892         // initial fulfill/CS.
1893         assert!(nodes[1].node.claim_funds(payment_preimage_1));
1894         check_added_monitors!(nodes[1], 1);
1895         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1896
1897         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1898         // remove the second HTLC when we send the HTLC back from B to A.
1899         assert!(nodes[1].node.claim_funds(payment_preimage_2));
1900         check_added_monitors!(nodes[1], 1);
1901         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1902
1903         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1904         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1905         check_added_monitors!(nodes[0], 1);
1906         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1907         expect_payment_sent!(nodes[0], payment_preimage_1);
1908
1909         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1910         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1911         check_added_monitors!(nodes[1], 1);
1912         // B is already AwaitingRAA, so cant generate a CS here
1913         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1914
1915         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1916         check_added_monitors!(nodes[1], 1);
1917         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1918
1919         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1920         check_added_monitors!(nodes[0], 1);
1921         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1922
1923         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1924         check_added_monitors!(nodes[1], 1);
1925         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1926
1927         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1928         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1929         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1930         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1931         // on-chain as necessary).
1932         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1933         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1934         check_added_monitors!(nodes[0], 1);
1935         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1936         expect_payment_sent!(nodes[0], payment_preimage_2);
1937
1938         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1939         check_added_monitors!(nodes[1], 1);
1940         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1941
1942         expect_pending_htlcs_forwardable!(nodes[1]);
1943         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
1944
1945         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1946         // resolve the second HTLC from A's point of view.
1947         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1948         check_added_monitors!(nodes[0], 1);
1949         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1950
1951         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1952         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1953         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
1954         let send_2 = {
1955                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
1956                 check_added_monitors!(nodes[1], 1);
1957                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1958                 assert_eq!(events.len(), 1);
1959                 SendEvent::from_event(events.remove(0))
1960         };
1961
1962         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1963         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1964         check_added_monitors!(nodes[0], 1);
1965         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1966
1967         // Now just resolve all the outstanding messages/HTLCs for completeness...
1968
1969         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1970         check_added_monitors!(nodes[1], 1);
1971         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1972
1973         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1974         check_added_monitors!(nodes[1], 1);
1975
1976         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1977         check_added_monitors!(nodes[0], 1);
1978         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1979
1980         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1981         check_added_monitors!(nodes[1], 1);
1982         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1983
1984         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1985         check_added_monitors!(nodes[0], 1);
1986
1987         expect_pending_htlcs_forwardable!(nodes[0]);
1988         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
1989
1990         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
1991         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
1992 }
1993
1994 #[test]
1995 fn channel_monitor_network_test() {
1996         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1997         // tests that ChannelMonitor is able to recover from various states.
1998         let chanmon_cfgs = create_chanmon_cfgs(5);
1999         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2000         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2001         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2002
2003         // Create some initial channels
2004         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2005         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2006         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2007         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2008
2009         // Make sure all nodes are at the same starting height
2010         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2011         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2012         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2013         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2014         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2015
2016         // Rebalance the network a bit by relaying one payment through all the channels...
2017         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2018         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2019         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2020         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2021
2022         // Simple case with no pending HTLCs:
2023         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2024         check_added_monitors!(nodes[1], 1);
2025         check_closed_broadcast!(nodes[1], false);
2026         {
2027                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2028                 assert_eq!(node_txn.len(), 1);
2029                 mine_transaction(&nodes[0], &node_txn[0]);
2030                 check_added_monitors!(nodes[0], 1);
2031                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2032         }
2033         check_closed_broadcast!(nodes[0], true);
2034         assert_eq!(nodes[0].node.list_channels().len(), 0);
2035         assert_eq!(nodes[1].node.list_channels().len(), 1);
2036         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2037         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2038
2039         // One pending HTLC is discarded by the force-close:
2040         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2041
2042         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2043         // broadcasted until we reach the timelock time).
2044         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2045         check_closed_broadcast!(nodes[1], false);
2046         check_added_monitors!(nodes[1], 1);
2047         {
2048                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2049                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2050                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2051                 mine_transaction(&nodes[2], &node_txn[0]);
2052                 check_added_monitors!(nodes[2], 1);
2053                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2054         }
2055         check_closed_broadcast!(nodes[2], true);
2056         assert_eq!(nodes[1].node.list_channels().len(), 0);
2057         assert_eq!(nodes[2].node.list_channels().len(), 1);
2058         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2059         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2060
2061         macro_rules! claim_funds {
2062                 ($node: expr, $prev_node: expr, $preimage: expr) => {
2063                         {
2064                                 assert!($node.node.claim_funds($preimage));
2065                                 check_added_monitors!($node, 1);
2066
2067                                 let events = $node.node.get_and_clear_pending_msg_events();
2068                                 assert_eq!(events.len(), 1);
2069                                 match events[0] {
2070                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2071                                                 assert!(update_add_htlcs.is_empty());
2072                                                 assert!(update_fail_htlcs.is_empty());
2073                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2074                                         },
2075                                         _ => panic!("Unexpected event"),
2076                                 };
2077                         }
2078                 }
2079         }
2080
2081         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2082         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2083         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2084         check_added_monitors!(nodes[2], 1);
2085         check_closed_broadcast!(nodes[2], false);
2086         let node2_commitment_txid;
2087         {
2088                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2089                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2090                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2091                 node2_commitment_txid = node_txn[0].txid();
2092
2093                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2094                 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2095                 mine_transaction(&nodes[3], &node_txn[0]);
2096                 check_added_monitors!(nodes[3], 1);
2097                 check_preimage_claim(&nodes[3], &node_txn);
2098         }
2099         check_closed_broadcast!(nodes[3], true);
2100         assert_eq!(nodes[2].node.list_channels().len(), 0);
2101         assert_eq!(nodes[3].node.list_channels().len(), 1);
2102         check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2103         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2104
2105         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2106         // confusing us in the following tests.
2107         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2108
2109         // One pending HTLC to time out:
2110         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2111         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2112         // buffer space).
2113
2114         let (close_chan_update_1, close_chan_update_2) = {
2115                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2116                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2117                 assert_eq!(events.len(), 2);
2118                 let close_chan_update_1 = match events[0] {
2119                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2120                                 msg.clone()
2121                         },
2122                         _ => panic!("Unexpected event"),
2123                 };
2124                 match events[1] {
2125                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2126                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2127                         },
2128                         _ => panic!("Unexpected event"),
2129                 }
2130                 check_added_monitors!(nodes[3], 1);
2131
2132                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2133                 {
2134                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2135                         node_txn.retain(|tx| {
2136                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2137                                         false
2138                                 } else { true }
2139                         });
2140                 }
2141
2142                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2143
2144                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2145                 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2146
2147                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2148                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2149                 assert_eq!(events.len(), 2);
2150                 let close_chan_update_2 = match events[0] {
2151                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2152                                 msg.clone()
2153                         },
2154                         _ => panic!("Unexpected event"),
2155                 };
2156                 match events[1] {
2157                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2158                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2159                         },
2160                         _ => panic!("Unexpected event"),
2161                 }
2162                 check_added_monitors!(nodes[4], 1);
2163                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2164
2165                 mine_transaction(&nodes[4], &node_txn[0]);
2166                 check_preimage_claim(&nodes[4], &node_txn);
2167                 (close_chan_update_1, close_chan_update_2)
2168         };
2169         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2170         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2171         assert_eq!(nodes[3].node.list_channels().len(), 0);
2172         assert_eq!(nodes[4].node.list_channels().len(), 0);
2173
2174         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2175         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2176         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2177 }
2178
2179 #[test]
2180 fn test_justice_tx() {
2181         // Test justice txn built on revoked HTLC-Success tx, against both sides
2182         let mut alice_config = UserConfig::default();
2183         alice_config.channel_options.announced_channel = true;
2184         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2185         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2186         let mut bob_config = UserConfig::default();
2187         bob_config.channel_options.announced_channel = true;
2188         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2189         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2190         let user_cfgs = [Some(alice_config), Some(bob_config)];
2191         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2192         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2193         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2194         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2195         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2196         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2197         // Create some new channels:
2198         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2199
2200         // A pending HTLC which will be revoked:
2201         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2202         // Get the will-be-revoked local txn from nodes[0]
2203         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2204         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2205         assert_eq!(revoked_local_txn[0].input.len(), 1);
2206         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2207         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2208         assert_eq!(revoked_local_txn[1].input.len(), 1);
2209         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2210         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2211         // Revoke the old state
2212         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2213
2214         {
2215                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2216                 {
2217                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2218                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2219                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2220
2221                         check_spends!(node_txn[0], revoked_local_txn[0]);
2222                         node_txn.swap_remove(0);
2223                         node_txn.truncate(1);
2224                 }
2225                 check_added_monitors!(nodes[1], 1);
2226                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2227                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2228
2229                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2230                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2231                 // Verify broadcast of revoked HTLC-timeout
2232                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2233                 check_added_monitors!(nodes[0], 1);
2234                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2235                 // Broadcast revoked HTLC-timeout on node 1
2236                 mine_transaction(&nodes[1], &node_txn[1]);
2237                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2238         }
2239         get_announce_close_broadcast_events(&nodes, 0, 1);
2240
2241         assert_eq!(nodes[0].node.list_channels().len(), 0);
2242         assert_eq!(nodes[1].node.list_channels().len(), 0);
2243
2244         // We test justice_tx build by A on B's revoked HTLC-Success tx
2245         // Create some new channels:
2246         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2247         {
2248                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2249                 node_txn.clear();
2250         }
2251
2252         // A pending HTLC which will be revoked:
2253         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2254         // Get the will-be-revoked local txn from B
2255         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2256         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2257         assert_eq!(revoked_local_txn[0].input.len(), 1);
2258         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2259         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2260         // Revoke the old state
2261         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2262         {
2263                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2264                 {
2265                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2266                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2267                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2268
2269                         check_spends!(node_txn[0], revoked_local_txn[0]);
2270                         node_txn.swap_remove(0);
2271                 }
2272                 check_added_monitors!(nodes[0], 1);
2273                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2274
2275                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2276                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2277                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2278                 check_added_monitors!(nodes[1], 1);
2279                 mine_transaction(&nodes[0], &node_txn[1]);
2280                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2281                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2282         }
2283         get_announce_close_broadcast_events(&nodes, 0, 1);
2284         assert_eq!(nodes[0].node.list_channels().len(), 0);
2285         assert_eq!(nodes[1].node.list_channels().len(), 0);
2286 }
2287
2288 #[test]
2289 fn revoked_output_claim() {
2290         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2291         // transaction is broadcast by its counterparty
2292         let chanmon_cfgs = create_chanmon_cfgs(2);
2293         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2294         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2295         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2296         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2297         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2298         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2299         assert_eq!(revoked_local_txn.len(), 1);
2300         // Only output is the full channel value back to nodes[0]:
2301         assert_eq!(revoked_local_txn[0].output.len(), 1);
2302         // Send a payment through, updating everyone's latest commitment txn
2303         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2304
2305         // Inform nodes[1] that nodes[0] broadcast a stale tx
2306         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2307         check_added_monitors!(nodes[1], 1);
2308         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2309         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2310         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2311
2312         check_spends!(node_txn[0], revoked_local_txn[0]);
2313         check_spends!(node_txn[1], chan_1.3);
2314
2315         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2316         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2317         get_announce_close_broadcast_events(&nodes, 0, 1);
2318         check_added_monitors!(nodes[0], 1);
2319         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2320 }
2321
2322 #[test]
2323 fn claim_htlc_outputs_shared_tx() {
2324         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2325         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2326         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2327         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2328         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2329         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2330
2331         // Create some new channel:
2332         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2333
2334         // Rebalance the network to generate htlc in the two directions
2335         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2336         // 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
2337         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2338         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2339
2340         // Get the will-be-revoked local txn from node[0]
2341         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2342         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2343         assert_eq!(revoked_local_txn[0].input.len(), 1);
2344         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2345         assert_eq!(revoked_local_txn[1].input.len(), 1);
2346         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2347         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2348         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2349
2350         //Revoke the old state
2351         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2352
2353         {
2354                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2355                 check_added_monitors!(nodes[0], 1);
2356                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2357                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2358                 check_added_monitors!(nodes[1], 1);
2359                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2360                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2361                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2362
2363                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2364                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2365
2366                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2367                 check_spends!(node_txn[0], revoked_local_txn[0]);
2368
2369                 let mut witness_lens = BTreeSet::new();
2370                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2371                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2372                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2373                 assert_eq!(witness_lens.len(), 3);
2374                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2375                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2376                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2377
2378                 // Next nodes[1] broadcasts its current local tx state:
2379                 assert_eq!(node_txn[1].input.len(), 1);
2380                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2381         }
2382         get_announce_close_broadcast_events(&nodes, 0, 1);
2383         assert_eq!(nodes[0].node.list_channels().len(), 0);
2384         assert_eq!(nodes[1].node.list_channels().len(), 0);
2385 }
2386
2387 #[test]
2388 fn claim_htlc_outputs_single_tx() {
2389         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2390         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2391         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2392         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2393         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2394         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2395
2396         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2397
2398         // Rebalance the network to generate htlc in the two directions
2399         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2400         // 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
2401         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2402         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2403         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2404
2405         // Get the will-be-revoked local txn from node[0]
2406         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2407
2408         //Revoke the old state
2409         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2410
2411         {
2412                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2413                 check_added_monitors!(nodes[0], 1);
2414                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2415                 check_added_monitors!(nodes[1], 1);
2416                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2417                 let mut events = nodes[0].node.get_and_clear_pending_events();
2418                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2419                 match events[1] {
2420                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2421                         _ => panic!("Unexpected event"),
2422                 }
2423
2424                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2425                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2426
2427                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2428                 assert_eq!(node_txn.len(), 9);
2429                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2430                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2431                 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2432                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2433
2434                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2435                 assert_eq!(node_txn[0].input.len(), 1);
2436                 check_spends!(node_txn[0], chan_1.3);
2437                 assert_eq!(node_txn[1].input.len(), 1);
2438                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2439                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2440                 check_spends!(node_txn[1], node_txn[0]);
2441
2442                 // Justice transactions are indices 1-2-4
2443                 assert_eq!(node_txn[2].input.len(), 1);
2444                 assert_eq!(node_txn[3].input.len(), 1);
2445                 assert_eq!(node_txn[4].input.len(), 1);
2446
2447                 check_spends!(node_txn[2], revoked_local_txn[0]);
2448                 check_spends!(node_txn[3], revoked_local_txn[0]);
2449                 check_spends!(node_txn[4], revoked_local_txn[0]);
2450
2451                 let mut witness_lens = BTreeSet::new();
2452                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2453                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2454                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2455                 assert_eq!(witness_lens.len(), 3);
2456                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2457                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2458                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2459         }
2460         get_announce_close_broadcast_events(&nodes, 0, 1);
2461         assert_eq!(nodes[0].node.list_channels().len(), 0);
2462         assert_eq!(nodes[1].node.list_channels().len(), 0);
2463 }
2464
2465 #[test]
2466 fn test_htlc_on_chain_success() {
2467         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2468         // the preimage backward accordingly. So here we test that ChannelManager is
2469         // broadcasting the right event to other nodes in payment path.
2470         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2471         // A --------------------> B ----------------------> C (preimage)
2472         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2473         // commitment transaction was broadcast.
2474         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2475         // towards B.
2476         // B should be able to claim via preimage if A then broadcasts its local tx.
2477         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2478         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2479         // PaymentSent event).
2480
2481         let chanmon_cfgs = create_chanmon_cfgs(3);
2482         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2483         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2484         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2485
2486         // Create some initial channels
2487         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2488         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2489
2490         // Ensure all nodes are at the same height
2491         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2492         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2493         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2494         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2495
2496         // Rebalance the network a bit by relaying one payment through all the channels...
2497         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2498         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2499
2500         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2501         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2502
2503         // Broadcast legit commitment tx from C on B's chain
2504         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2505         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2506         assert_eq!(commitment_tx.len(), 1);
2507         check_spends!(commitment_tx[0], chan_2.3);
2508         nodes[2].node.claim_funds(our_payment_preimage);
2509         nodes[2].node.claim_funds(our_payment_preimage_2);
2510         check_added_monitors!(nodes[2], 2);
2511         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2512         assert!(updates.update_add_htlcs.is_empty());
2513         assert!(updates.update_fail_htlcs.is_empty());
2514         assert!(updates.update_fail_malformed_htlcs.is_empty());
2515         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2516
2517         mine_transaction(&nodes[2], &commitment_tx[0]);
2518         check_closed_broadcast!(nodes[2], true);
2519         check_added_monitors!(nodes[2], 1);
2520         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2521         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)
2522         assert_eq!(node_txn.len(), 5);
2523         assert_eq!(node_txn[0], node_txn[3]);
2524         assert_eq!(node_txn[1], node_txn[4]);
2525         assert_eq!(node_txn[2], commitment_tx[0]);
2526         check_spends!(node_txn[0], commitment_tx[0]);
2527         check_spends!(node_txn[1], commitment_tx[0]);
2528         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2529         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2530         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2531         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2532         assert_eq!(node_txn[0].lock_time, 0);
2533         assert_eq!(node_txn[1].lock_time, 0);
2534
2535         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2536         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2537         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2538         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2539         {
2540                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2541                 assert_eq!(added_monitors.len(), 1);
2542                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2543                 added_monitors.clear();
2544         }
2545         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2546         assert_eq!(forwarded_events.len(), 3);
2547         match forwarded_events[0] {
2548                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2549                 _ => panic!("Unexpected event"),
2550         }
2551         if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2552                 } else { panic!(); }
2553         if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[2] {
2554                 } else { panic!(); }
2555         let events = nodes[1].node.get_and_clear_pending_msg_events();
2556         {
2557                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2558                 assert_eq!(added_monitors.len(), 2);
2559                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2560                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2561                 added_monitors.clear();
2562         }
2563         assert_eq!(events.len(), 3);
2564         match events[0] {
2565                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2566                 _ => panic!("Unexpected event"),
2567         }
2568         match events[1] {
2569                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2570                 _ => panic!("Unexpected event"),
2571         }
2572
2573         match events[2] {
2574                 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, .. } } => {
2575                         assert!(update_add_htlcs.is_empty());
2576                         assert!(update_fail_htlcs.is_empty());
2577                         assert_eq!(update_fulfill_htlcs.len(), 1);
2578                         assert!(update_fail_malformed_htlcs.is_empty());
2579                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2580                 },
2581                 _ => panic!("Unexpected event"),
2582         };
2583         macro_rules! check_tx_local_broadcast {
2584                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2585                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2586                         assert_eq!(node_txn.len(), 3);
2587                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2588                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2589                         check_spends!(node_txn[1], $commitment_tx);
2590                         check_spends!(node_txn[2], $commitment_tx);
2591                         assert_ne!(node_txn[1].lock_time, 0);
2592                         assert_ne!(node_txn[2].lock_time, 0);
2593                         if $htlc_offered {
2594                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2595                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2596                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2597                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2598                         } else {
2599                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2600                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2601                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2602                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2603                         }
2604                         check_spends!(node_txn[0], $chan_tx);
2605                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2606                         node_txn.clear();
2607                 } }
2608         }
2609         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2610         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2611         // timeout-claim of the output that nodes[2] just claimed via success.
2612         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2613
2614         // Broadcast legit commitment tx from A on B's chain
2615         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2616         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2617         check_spends!(node_a_commitment_tx[0], chan_1.3);
2618         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2619         check_closed_broadcast!(nodes[1], true);
2620         check_added_monitors!(nodes[1], 1);
2621         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2622         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2623         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2624         let commitment_spend =
2625                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2626                         check_spends!(node_txn[1], commitment_tx[0]);
2627                         check_spends!(node_txn[2], commitment_tx[0]);
2628                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2629                         &node_txn[0]
2630                 } else {
2631                         check_spends!(node_txn[0], commitment_tx[0]);
2632                         check_spends!(node_txn[1], commitment_tx[0]);
2633                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2634                         &node_txn[2]
2635                 };
2636
2637         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2638         assert_eq!(commitment_spend.input.len(), 2);
2639         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2640         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2641         assert_eq!(commitment_spend.lock_time, 0);
2642         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2643         check_spends!(node_txn[3], chan_1.3);
2644         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2645         check_spends!(node_txn[4], node_txn[3]);
2646         check_spends!(node_txn[5], node_txn[3]);
2647         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2648         // we already checked the same situation with A.
2649
2650         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2651         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2652         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2653         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2654         check_closed_broadcast!(nodes[0], true);
2655         check_added_monitors!(nodes[0], 1);
2656         let events = nodes[0].node.get_and_clear_pending_events();
2657         assert_eq!(events.len(), 3);
2658         let mut first_claimed = false;
2659         for event in events {
2660                 match event {
2661                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2662                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2663                                         assert!(!first_claimed);
2664                                         first_claimed = true;
2665                                 } else {
2666                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2667                                         assert_eq!(payment_hash, payment_hash_2);
2668                                 }
2669                         },
2670                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2671                         _ => panic!("Unexpected event"),
2672                 }
2673         }
2674         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2675 }
2676
2677 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2678         // Test that in case of a unilateral close onchain, we detect the state of output and
2679         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2680         // broadcasting the right event to other nodes in payment path.
2681         // A ------------------> B ----------------------> C (timeout)
2682         //    B's commitment tx                 C's commitment tx
2683         //            \                                  \
2684         //         B's HTLC timeout tx               B's timeout tx
2685
2686         let chanmon_cfgs = create_chanmon_cfgs(3);
2687         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2688         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2689         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2690         *nodes[0].connect_style.borrow_mut() = connect_style;
2691         *nodes[1].connect_style.borrow_mut() = connect_style;
2692         *nodes[2].connect_style.borrow_mut() = connect_style;
2693
2694         // Create some intial channels
2695         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2696         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2697
2698         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2699         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2700         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2701
2702         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2703
2704         // Broadcast legit commitment tx from C on B's chain
2705         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2706         check_spends!(commitment_tx[0], chan_2.3);
2707         nodes[2].node.fail_htlc_backwards(&payment_hash);
2708         check_added_monitors!(nodes[2], 0);
2709         expect_pending_htlcs_forwardable!(nodes[2]);
2710         check_added_monitors!(nodes[2], 1);
2711
2712         let events = nodes[2].node.get_and_clear_pending_msg_events();
2713         assert_eq!(events.len(), 1);
2714         match events[0] {
2715                 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, .. } } => {
2716                         assert!(update_add_htlcs.is_empty());
2717                         assert!(!update_fail_htlcs.is_empty());
2718                         assert!(update_fulfill_htlcs.is_empty());
2719                         assert!(update_fail_malformed_htlcs.is_empty());
2720                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2721                 },
2722                 _ => panic!("Unexpected event"),
2723         };
2724         mine_transaction(&nodes[2], &commitment_tx[0]);
2725         check_closed_broadcast!(nodes[2], true);
2726         check_added_monitors!(nodes[2], 1);
2727         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2728         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2729         assert_eq!(node_txn.len(), 1);
2730         check_spends!(node_txn[0], chan_2.3);
2731         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2732
2733         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2734         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2735         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2736         mine_transaction(&nodes[1], &commitment_tx[0]);
2737         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2738         let timeout_tx;
2739         {
2740                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2741                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2742                 assert_eq!(node_txn[0], node_txn[3]);
2743                 assert_eq!(node_txn[1], node_txn[4]);
2744
2745                 check_spends!(node_txn[2], commitment_tx[0]);
2746                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2747
2748                 check_spends!(node_txn[0], chan_2.3);
2749                 check_spends!(node_txn[1], node_txn[0]);
2750                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2751                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2752
2753                 timeout_tx = node_txn[2].clone();
2754                 node_txn.clear();
2755         }
2756
2757         mine_transaction(&nodes[1], &timeout_tx);
2758         check_added_monitors!(nodes[1], 1);
2759         check_closed_broadcast!(nodes[1], true);
2760         {
2761                 // B will rebroadcast a fee-bumped timeout transaction here.
2762                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2763                 assert_eq!(node_txn.len(), 1);
2764                 check_spends!(node_txn[0], commitment_tx[0]);
2765         }
2766
2767         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2768         {
2769                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2770                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2771                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2772                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2773                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2774                 if node_txn.len() == 1 {
2775                         check_spends!(node_txn[0], chan_2.3);
2776                 } else {
2777                         assert_eq!(node_txn.len(), 0);
2778                 }
2779         }
2780
2781         expect_pending_htlcs_forwardable!(nodes[1]);
2782         check_added_monitors!(nodes[1], 1);
2783         let events = nodes[1].node.get_and_clear_pending_msg_events();
2784         assert_eq!(events.len(), 1);
2785         match events[0] {
2786                 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, .. } } => {
2787                         assert!(update_add_htlcs.is_empty());
2788                         assert!(!update_fail_htlcs.is_empty());
2789                         assert!(update_fulfill_htlcs.is_empty());
2790                         assert!(update_fail_malformed_htlcs.is_empty());
2791                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2792                 },
2793                 _ => panic!("Unexpected event"),
2794         };
2795
2796         // Broadcast legit commitment tx from B on A's chain
2797         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2798         check_spends!(commitment_tx[0], chan_1.3);
2799
2800         mine_transaction(&nodes[0], &commitment_tx[0]);
2801         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2802
2803         check_closed_broadcast!(nodes[0], true);
2804         check_added_monitors!(nodes[0], 1);
2805         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2806         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2807         assert_eq!(node_txn.len(), 2);
2808         check_spends!(node_txn[0], chan_1.3);
2809         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2810         check_spends!(node_txn[1], commitment_tx[0]);
2811         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2812 }
2813
2814 #[test]
2815 fn test_htlc_on_chain_timeout() {
2816         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2817         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2818         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2819 }
2820
2821 #[test]
2822 fn test_simple_commitment_revoked_fail_backward() {
2823         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2824         // and fail backward accordingly.
2825
2826         let chanmon_cfgs = create_chanmon_cfgs(3);
2827         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2828         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2829         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2830
2831         // Create some initial channels
2832         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2833         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2834
2835         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2836         // Get the will-be-revoked local txn from nodes[2]
2837         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2838         // Revoke the old state
2839         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2840
2841         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2842
2843         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2844         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2845         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2846         check_added_monitors!(nodes[1], 1);
2847         check_closed_broadcast!(nodes[1], true);
2848
2849         expect_pending_htlcs_forwardable!(nodes[1]);
2850         check_added_monitors!(nodes[1], 1);
2851         let events = nodes[1].node.get_and_clear_pending_msg_events();
2852         assert_eq!(events.len(), 1);
2853         match events[0] {
2854                 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, .. } } => {
2855                         assert!(update_add_htlcs.is_empty());
2856                         assert_eq!(update_fail_htlcs.len(), 1);
2857                         assert!(update_fulfill_htlcs.is_empty());
2858                         assert!(update_fail_malformed_htlcs.is_empty());
2859                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2860
2861                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2862                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2863                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
2864                 },
2865                 _ => panic!("Unexpected event"),
2866         }
2867 }
2868
2869 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2870         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2871         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2872         // commitment transaction anymore.
2873         // To do this, we have the peer which will broadcast a revoked commitment transaction send
2874         // a number of update_fail/commitment_signed updates without ever sending the RAA in
2875         // response to our commitment_signed. This is somewhat misbehavior-y, though not
2876         // technically disallowed and we should probably handle it reasonably.
2877         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2878         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2879         // transactions:
2880         // * Once we move it out of our holding cell/add it, we will immediately include it in a
2881         //   commitment_signed (implying it will be in the latest remote commitment transaction).
2882         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2883         //   and once they revoke the previous commitment transaction (allowing us to send a new
2884         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2885         let chanmon_cfgs = create_chanmon_cfgs(3);
2886         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2887         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2888         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2889
2890         // Create some initial channels
2891         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2892         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2893
2894         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 });
2895         // Get the will-be-revoked local txn from nodes[2]
2896         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2897         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2898         // Revoke the old state
2899         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2900
2901         let value = if use_dust {
2902                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2903                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2904                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
2905         } else { 3000000 };
2906
2907         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2908         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2909         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2910
2911         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2912         expect_pending_htlcs_forwardable!(nodes[2]);
2913         check_added_monitors!(nodes[2], 1);
2914         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2915         assert!(updates.update_add_htlcs.is_empty());
2916         assert!(updates.update_fulfill_htlcs.is_empty());
2917         assert!(updates.update_fail_malformed_htlcs.is_empty());
2918         assert_eq!(updates.update_fail_htlcs.len(), 1);
2919         assert!(updates.update_fee.is_none());
2920         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2921         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2922         // Drop the last RAA from 3 -> 2
2923
2924         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2925         expect_pending_htlcs_forwardable!(nodes[2]);
2926         check_added_monitors!(nodes[2], 1);
2927         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2928         assert!(updates.update_add_htlcs.is_empty());
2929         assert!(updates.update_fulfill_htlcs.is_empty());
2930         assert!(updates.update_fail_malformed_htlcs.is_empty());
2931         assert_eq!(updates.update_fail_htlcs.len(), 1);
2932         assert!(updates.update_fee.is_none());
2933         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2934         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2935         check_added_monitors!(nodes[1], 1);
2936         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2937         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2938         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2939         check_added_monitors!(nodes[2], 1);
2940
2941         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2942         expect_pending_htlcs_forwardable!(nodes[2]);
2943         check_added_monitors!(nodes[2], 1);
2944         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2945         assert!(updates.update_add_htlcs.is_empty());
2946         assert!(updates.update_fulfill_htlcs.is_empty());
2947         assert!(updates.update_fail_malformed_htlcs.is_empty());
2948         assert_eq!(updates.update_fail_htlcs.len(), 1);
2949         assert!(updates.update_fee.is_none());
2950         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2951         // At this point first_payment_hash has dropped out of the latest two commitment
2952         // transactions that nodes[1] is tracking...
2953         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2954         check_added_monitors!(nodes[1], 1);
2955         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2956         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2957         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2958         check_added_monitors!(nodes[2], 1);
2959
2960         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2961         // on nodes[2]'s RAA.
2962         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
2963         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
2964         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2965         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2966         check_added_monitors!(nodes[1], 0);
2967
2968         if deliver_bs_raa {
2969                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2970                 // One monitor for the new revocation preimage, no second on as we won't generate a new
2971                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2972                 check_added_monitors!(nodes[1], 1);
2973                 let events = nodes[1].node.get_and_clear_pending_events();
2974                 assert_eq!(events.len(), 1);
2975                 match events[0] {
2976                         Event::PendingHTLCsForwardable { .. } => { },
2977                         _ => panic!("Unexpected event"),
2978                 };
2979                 // Deliberately don't process the pending fail-back so they all fail back at once after
2980                 // block connection just like the !deliver_bs_raa case
2981         }
2982
2983         let mut failed_htlcs = HashSet::new();
2984         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2985
2986         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2987         check_added_monitors!(nodes[1], 1);
2988         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2989
2990         let events = nodes[1].node.get_and_clear_pending_events();
2991         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2992         match events[0] {
2993                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
2994                 _ => panic!("Unexepected event"),
2995         }
2996         match events[1] {
2997                 Event::PaymentPathFailed { ref payment_hash, .. } => {
2998                         assert_eq!(*payment_hash, fourth_payment_hash);
2999                 },
3000                 _ => panic!("Unexpected event"),
3001         }
3002         if !deliver_bs_raa {
3003                 match events[2] {
3004                         Event::PendingHTLCsForwardable { .. } => { },
3005                         _ => panic!("Unexpected event"),
3006                 };
3007         }
3008         nodes[1].node.process_pending_htlc_forwards();
3009         check_added_monitors!(nodes[1], 1);
3010
3011         let events = nodes[1].node.get_and_clear_pending_msg_events();
3012         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3013         match events[if deliver_bs_raa { 1 } else { 0 }] {
3014                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3015                 _ => panic!("Unexpected event"),
3016         }
3017         match events[if deliver_bs_raa { 2 } else { 1 }] {
3018                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3019                         assert_eq!(channel_id, chan_2.2);
3020                         assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3021                 },
3022                 _ => panic!("Unexpected event"),
3023         }
3024         if deliver_bs_raa {
3025                 match events[0] {
3026                         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, .. } } => {
3027                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3028                                 assert_eq!(update_add_htlcs.len(), 1);
3029                                 assert!(update_fulfill_htlcs.is_empty());
3030                                 assert!(update_fail_htlcs.is_empty());
3031                                 assert!(update_fail_malformed_htlcs.is_empty());
3032                         },
3033                         _ => panic!("Unexpected event"),
3034                 }
3035         }
3036         match events[if deliver_bs_raa { 3 } else { 2 }] {
3037                 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, .. } } => {
3038                         assert!(update_add_htlcs.is_empty());
3039                         assert_eq!(update_fail_htlcs.len(), 3);
3040                         assert!(update_fulfill_htlcs.is_empty());
3041                         assert!(update_fail_malformed_htlcs.is_empty());
3042                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3043
3044                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3045                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3046                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3047
3048                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3049
3050                         let events = nodes[0].node.get_and_clear_pending_events();
3051                         assert_eq!(events.len(), 3);
3052                         match events[0] {
3053                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3054                                         assert!(failed_htlcs.insert(payment_hash.0));
3055                                         // If we delivered B's RAA we got an unknown preimage error, not something
3056                                         // that we should update our routing table for.
3057                                         if !deliver_bs_raa {
3058                                                 assert!(network_update.is_some());
3059                                         }
3060                                 },
3061                                 _ => panic!("Unexpected event"),
3062                         }
3063                         match events[1] {
3064                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3065                                         assert!(failed_htlcs.insert(payment_hash.0));
3066                                         assert!(network_update.is_some());
3067                                 },
3068                                 _ => panic!("Unexpected event"),
3069                         }
3070                         match events[2] {
3071                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3072                                         assert!(failed_htlcs.insert(payment_hash.0));
3073                                         assert!(network_update.is_some());
3074                                 },
3075                                 _ => panic!("Unexpected event"),
3076                         }
3077                 },
3078                 _ => panic!("Unexpected event"),
3079         }
3080
3081         assert!(failed_htlcs.contains(&first_payment_hash.0));
3082         assert!(failed_htlcs.contains(&second_payment_hash.0));
3083         assert!(failed_htlcs.contains(&third_payment_hash.0));
3084 }
3085
3086 #[test]
3087 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3088         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3089         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3090         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3091         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3092 }
3093
3094 #[test]
3095 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3096         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3097         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3098         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3099         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3100 }
3101
3102 #[test]
3103 fn fail_backward_pending_htlc_upon_channel_failure() {
3104         let chanmon_cfgs = create_chanmon_cfgs(2);
3105         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3106         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3107         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3108         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3109
3110         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3111         {
3112                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3113                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3114                 check_added_monitors!(nodes[0], 1);
3115
3116                 let payment_event = {
3117                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3118                         assert_eq!(events.len(), 1);
3119                         SendEvent::from_event(events.remove(0))
3120                 };
3121                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3122                 assert_eq!(payment_event.msgs.len(), 1);
3123         }
3124
3125         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3126         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3127         {
3128                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3129                 check_added_monitors!(nodes[0], 0);
3130
3131                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3132         }
3133
3134         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3135         {
3136                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3137
3138                 let secp_ctx = Secp256k1::new();
3139                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3140                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3141                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3142                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3143                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3144
3145                 // Send a 0-msat update_add_htlc to fail the channel.
3146                 let update_add_htlc = msgs::UpdateAddHTLC {
3147                         channel_id: chan.2,
3148                         htlc_id: 0,
3149                         amount_msat: 0,
3150                         payment_hash,
3151                         cltv_expiry,
3152                         onion_routing_packet,
3153                 };
3154                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3155         }
3156         let events = nodes[0].node.get_and_clear_pending_events();
3157         assert_eq!(events.len(), 2);
3158         // Check that Alice fails backward the pending HTLC from the second payment.
3159         match events[0] {
3160                 Event::PaymentPathFailed { payment_hash, .. } => {
3161                         assert_eq!(payment_hash, failed_payment_hash);
3162                 },
3163                 _ => panic!("Unexpected event"),
3164         }
3165         match events[1] {
3166                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3167                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3168                 },
3169                 _ => panic!("Unexpected event {:?}", events[1]),
3170         }
3171         check_closed_broadcast!(nodes[0], true);
3172         check_added_monitors!(nodes[0], 1);
3173 }
3174
3175 #[test]
3176 fn test_htlc_ignore_latest_remote_commitment() {
3177         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3178         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3179         let chanmon_cfgs = create_chanmon_cfgs(2);
3180         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3181         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3182         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3183         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3184
3185         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3186         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3187         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3188         check_closed_broadcast!(nodes[0], true);
3189         check_added_monitors!(nodes[0], 1);
3190         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3191
3192         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3193         assert_eq!(node_txn.len(), 3);
3194         assert_eq!(node_txn[0], node_txn[1]);
3195
3196         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3197         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3198         check_closed_broadcast!(nodes[1], true);
3199         check_added_monitors!(nodes[1], 1);
3200         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3201
3202         // Duplicate the connect_block call since this may happen due to other listeners
3203         // registering new transactions
3204         header.prev_blockhash = header.block_hash();
3205         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3206 }
3207
3208 #[test]
3209 fn test_force_close_fail_back() {
3210         // Check which HTLCs are failed-backwards on channel force-closure
3211         let chanmon_cfgs = create_chanmon_cfgs(3);
3212         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3213         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3214         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3215         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3216         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3217
3218         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3219
3220         let mut payment_event = {
3221                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3222                 check_added_monitors!(nodes[0], 1);
3223
3224                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3225                 assert_eq!(events.len(), 1);
3226                 SendEvent::from_event(events.remove(0))
3227         };
3228
3229         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3230         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3231
3232         expect_pending_htlcs_forwardable!(nodes[1]);
3233
3234         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3235         assert_eq!(events_2.len(), 1);
3236         payment_event = SendEvent::from_event(events_2.remove(0));
3237         assert_eq!(payment_event.msgs.len(), 1);
3238
3239         check_added_monitors!(nodes[1], 1);
3240         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3241         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3242         check_added_monitors!(nodes[2], 1);
3243         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3244
3245         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3246         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3247         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3248
3249         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3250         check_closed_broadcast!(nodes[2], true);
3251         check_added_monitors!(nodes[2], 1);
3252         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3253         let tx = {
3254                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3255                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3256                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3257                 // back to nodes[1] upon timeout otherwise.
3258                 assert_eq!(node_txn.len(), 1);
3259                 node_txn.remove(0)
3260         };
3261
3262         mine_transaction(&nodes[1], &tx);
3263
3264         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3265         check_closed_broadcast!(nodes[1], true);
3266         check_added_monitors!(nodes[1], 1);
3267         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3268
3269         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3270         {
3271                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3272                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3273         }
3274         mine_transaction(&nodes[2], &tx);
3275         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3276         assert_eq!(node_txn.len(), 1);
3277         assert_eq!(node_txn[0].input.len(), 1);
3278         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3279         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3280         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3281
3282         check_spends!(node_txn[0], tx);
3283 }
3284
3285 #[test]
3286 fn test_dup_events_on_peer_disconnect() {
3287         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3288         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3289         // as we used to generate the event immediately upon receipt of the payment preimage in the
3290         // update_fulfill_htlc message.
3291
3292         let chanmon_cfgs = create_chanmon_cfgs(2);
3293         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3294         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3295         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3296         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3297
3298         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3299
3300         assert!(nodes[1].node.claim_funds(payment_preimage));
3301         check_added_monitors!(nodes[1], 1);
3302         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3303         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3304         expect_payment_sent!(nodes[0], payment_preimage);
3305
3306         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3307         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3308
3309         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3310         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3311 }
3312
3313 #[test]
3314 fn test_simple_peer_disconnect() {
3315         // Test that we can reconnect when there are no lost messages
3316         let chanmon_cfgs = create_chanmon_cfgs(3);
3317         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3318         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3319         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3320         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3321         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3322
3323         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3324         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3325         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3326
3327         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3328         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3329         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3330         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3331
3332         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3333         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3334         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3335
3336         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3337         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3338         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3339         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3340
3341         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3342         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3343
3344         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3345         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3346
3347         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3348         {
3349                 let events = nodes[0].node.get_and_clear_pending_events();
3350                 assert_eq!(events.len(), 2);
3351                 match events[0] {
3352                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3353                                 assert_eq!(payment_preimage, payment_preimage_3);
3354                                 assert_eq!(payment_hash, payment_hash_3);
3355                         },
3356                         _ => panic!("Unexpected event"),
3357                 }
3358                 match events[1] {
3359                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3360                                 assert_eq!(payment_hash, payment_hash_5);
3361                                 assert!(rejected_by_dest);
3362                         },
3363                         _ => panic!("Unexpected event"),
3364                 }
3365         }
3366
3367         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3368         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3369 }
3370
3371 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3372         // Test that we can reconnect when in-flight HTLC updates get dropped
3373         let chanmon_cfgs = create_chanmon_cfgs(2);
3374         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3375         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3376         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3377
3378         let mut as_funding_locked = None;
3379         if messages_delivered == 0 {
3380                 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3381                 as_funding_locked = Some(funding_locked);
3382                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3383                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3384                 // it before the channel_reestablish message.
3385         } else {
3386                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3387         }
3388
3389         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3390
3391         let payment_event = {
3392                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3393                 check_added_monitors!(nodes[0], 1);
3394
3395                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3396                 assert_eq!(events.len(), 1);
3397                 SendEvent::from_event(events.remove(0))
3398         };
3399         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3400
3401         if messages_delivered < 2 {
3402                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3403         } else {
3404                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3405                 if messages_delivered >= 3 {
3406                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3407                         check_added_monitors!(nodes[1], 1);
3408                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3409
3410                         if messages_delivered >= 4 {
3411                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3412                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3413                                 check_added_monitors!(nodes[0], 1);
3414
3415                                 if messages_delivered >= 5 {
3416                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3417                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3418                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3419                                         check_added_monitors!(nodes[0], 1);
3420
3421                                         if messages_delivered >= 6 {
3422                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3423                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3424                                                 check_added_monitors!(nodes[1], 1);
3425                                         }
3426                                 }
3427                         }
3428                 }
3429         }
3430
3431         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3432         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3433         if messages_delivered < 3 {
3434                 if simulate_broken_lnd {
3435                         // lnd has a long-standing bug where they send a funding_locked prior to a
3436                         // channel_reestablish if you reconnect prior to funding_locked time.
3437                         //
3438                         // Here we simulate that behavior, delivering a funding_locked immediately on
3439                         // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3440                         // in `reconnect_nodes` but we currently don't fail based on that.
3441                         //
3442                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3443                         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3444                 }
3445                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3446                 // received on either side, both sides will need to resend them.
3447                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3448         } else if messages_delivered == 3 {
3449                 // nodes[0] still wants its RAA + commitment_signed
3450                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3451         } else if messages_delivered == 4 {
3452                 // nodes[0] still wants its commitment_signed
3453                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3454         } else if messages_delivered == 5 {
3455                 // nodes[1] still wants its final RAA
3456                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3457         } else if messages_delivered == 6 {
3458                 // Everything was delivered...
3459                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3460         }
3461
3462         let events_1 = nodes[1].node.get_and_clear_pending_events();
3463         assert_eq!(events_1.len(), 1);
3464         match events_1[0] {
3465                 Event::PendingHTLCsForwardable { .. } => { },
3466                 _ => panic!("Unexpected event"),
3467         };
3468
3469         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3470         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3471         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3472
3473         nodes[1].node.process_pending_htlc_forwards();
3474
3475         let events_2 = nodes[1].node.get_and_clear_pending_events();
3476         assert_eq!(events_2.len(), 1);
3477         match events_2[0] {
3478                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3479                         assert_eq!(payment_hash_1, *payment_hash);
3480                         assert_eq!(amt, 1000000);
3481                         match &purpose {
3482                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3483                                         assert!(payment_preimage.is_none());
3484                                         assert_eq!(payment_secret_1, *payment_secret);
3485                                 },
3486                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3487                         }
3488                 },
3489                 _ => panic!("Unexpected event"),
3490         }
3491
3492         nodes[1].node.claim_funds(payment_preimage_1);
3493         check_added_monitors!(nodes[1], 1);
3494
3495         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3496         assert_eq!(events_3.len(), 1);
3497         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3498                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3499                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3500                         assert!(updates.update_add_htlcs.is_empty());
3501                         assert!(updates.update_fail_htlcs.is_empty());
3502                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3503                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3504                         assert!(updates.update_fee.is_none());
3505                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3506                 },
3507                 _ => panic!("Unexpected event"),
3508         };
3509
3510         if messages_delivered >= 1 {
3511                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3512
3513                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3514                 assert_eq!(events_4.len(), 1);
3515                 match events_4[0] {
3516                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3517                                 assert_eq!(payment_preimage_1, *payment_preimage);
3518                                 assert_eq!(payment_hash_1, *payment_hash);
3519                         },
3520                         _ => panic!("Unexpected event"),
3521                 }
3522
3523                 if messages_delivered >= 2 {
3524                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3525                         check_added_monitors!(nodes[0], 1);
3526                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3527
3528                         if messages_delivered >= 3 {
3529                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3530                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3531                                 check_added_monitors!(nodes[1], 1);
3532
3533                                 if messages_delivered >= 4 {
3534                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3535                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3536                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3537                                         check_added_monitors!(nodes[1], 1);
3538
3539                                         if messages_delivered >= 5 {
3540                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3541                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3542                                                 check_added_monitors!(nodes[0], 1);
3543                                         }
3544                                 }
3545                         }
3546                 }
3547         }
3548
3549         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3550         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3551         if messages_delivered < 2 {
3552                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3553                 if messages_delivered < 1 {
3554                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3555                         assert_eq!(events_4.len(), 1);
3556                         match events_4[0] {
3557                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3558                                         assert_eq!(payment_preimage_1, *payment_preimage);
3559                                         assert_eq!(payment_hash_1, *payment_hash);
3560                                 },
3561                                 _ => panic!("Unexpected event"),
3562                         }
3563                 } else {
3564                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3565                 }
3566         } else if messages_delivered == 2 {
3567                 // nodes[0] still wants its RAA + commitment_signed
3568                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3569         } else if messages_delivered == 3 {
3570                 // nodes[0] still wants its commitment_signed
3571                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3572         } else if messages_delivered == 4 {
3573                 // nodes[1] still wants its final RAA
3574                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3575         } else if messages_delivered == 5 {
3576                 // Everything was delivered...
3577                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3578         }
3579
3580         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3581         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3582         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3583
3584         // Channel should still work fine...
3585         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3586         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3587         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3588 }
3589
3590 #[test]
3591 fn test_drop_messages_peer_disconnect_a() {
3592         do_test_drop_messages_peer_disconnect(0, true);
3593         do_test_drop_messages_peer_disconnect(0, false);
3594         do_test_drop_messages_peer_disconnect(1, false);
3595         do_test_drop_messages_peer_disconnect(2, false);
3596 }
3597
3598 #[test]
3599 fn test_drop_messages_peer_disconnect_b() {
3600         do_test_drop_messages_peer_disconnect(3, false);
3601         do_test_drop_messages_peer_disconnect(4, false);
3602         do_test_drop_messages_peer_disconnect(5, false);
3603         do_test_drop_messages_peer_disconnect(6, false);
3604 }
3605
3606 #[test]
3607 fn test_funding_peer_disconnect() {
3608         // Test that we can lock in our funding tx while disconnected
3609         let chanmon_cfgs = create_chanmon_cfgs(2);
3610         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3611         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3612         let persister: test_utils::TestPersister;
3613         let new_chain_monitor: test_utils::TestChainMonitor;
3614         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3615         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3616         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3617
3618         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3619         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3620
3621         confirm_transaction(&nodes[0], &tx);
3622         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3623         let chan_id;
3624         assert_eq!(events_1.len(), 1);
3625         match events_1[0] {
3626                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3627                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3628                         chan_id = msg.channel_id;
3629                 },
3630                 _ => panic!("Unexpected event"),
3631         }
3632
3633         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3634
3635         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3636         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3637
3638         confirm_transaction(&nodes[1], &tx);
3639         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3640         assert_eq!(events_2.len(), 2);
3641         let funding_locked = match events_2[0] {
3642                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3643                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3644                         msg.clone()
3645                 },
3646                 _ => panic!("Unexpected event"),
3647         };
3648         let bs_announcement_sigs = match events_2[1] {
3649                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3650                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3651                         msg.clone()
3652                 },
3653                 _ => panic!("Unexpected event"),
3654         };
3655
3656         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3657
3658         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3659         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3660         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3661         assert_eq!(events_3.len(), 2);
3662         let as_announcement_sigs = match events_3[0] {
3663                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3664                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3665                         msg.clone()
3666                 },
3667                 _ => panic!("Unexpected event"),
3668         };
3669         let (as_announcement, as_update) = match events_3[1] {
3670                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3671                         (msg.clone(), update_msg.clone())
3672                 },
3673                 _ => panic!("Unexpected event"),
3674         };
3675
3676         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3677         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3678         assert_eq!(events_4.len(), 1);
3679         let (_, bs_update) = match events_4[0] {
3680                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3681                         (msg.clone(), update_msg.clone())
3682                 },
3683                 _ => panic!("Unexpected event"),
3684         };
3685
3686         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3687         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3688         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3689
3690         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3691         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3692         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3693
3694         // Check that after deserialization and reconnection we can still generate an identical
3695         // channel_announcement from the cached signatures.
3696         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3697
3698         let nodes_0_serialized = nodes[0].node.encode();
3699         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3700         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3701
3702         persister = test_utils::TestPersister::new();
3703         let keys_manager = &chanmon_cfgs[0].keys_manager;
3704         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);
3705         nodes[0].chain_monitor = &new_chain_monitor;
3706         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3707         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3708                 &mut chan_0_monitor_read, keys_manager).unwrap();
3709         assert!(chan_0_monitor_read.is_empty());
3710
3711         let mut nodes_0_read = &nodes_0_serialized[..];
3712         let (_, nodes_0_deserialized_tmp) = {
3713                 let mut channel_monitors = HashMap::new();
3714                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3715                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3716                         default_config: UserConfig::default(),
3717                         keys_manager,
3718                         fee_estimator: node_cfgs[0].fee_estimator,
3719                         chain_monitor: nodes[0].chain_monitor,
3720                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3721                         logger: nodes[0].logger,
3722                         channel_monitors,
3723                 }).unwrap()
3724         };
3725         nodes_0_deserialized = nodes_0_deserialized_tmp;
3726         assert!(nodes_0_read.is_empty());
3727
3728         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3729         nodes[0].node = &nodes_0_deserialized;
3730         check_added_monitors!(nodes[0], 1);
3731
3732         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3733
3734         // as_announcement should be re-generated exactly by broadcast_node_announcement.
3735         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3736         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3737         let mut found_announcement = false;
3738         for event in msgs.iter() {
3739                 match event {
3740                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3741                                 if *msg == as_announcement { found_announcement = true; }
3742                         },
3743                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3744                         _ => panic!("Unexpected event"),
3745                 }
3746         }
3747         assert!(found_announcement);
3748 }
3749
3750 #[test]
3751 fn test_drop_messages_peer_disconnect_dual_htlc() {
3752         // Test that we can handle reconnecting when both sides of a channel have pending
3753         // commitment_updates when we disconnect.
3754         let chanmon_cfgs = create_chanmon_cfgs(2);
3755         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3756         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3757         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3758         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3759
3760         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3761
3762         // Now try to send a second payment which will fail to send
3763         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3764         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3765         check_added_monitors!(nodes[0], 1);
3766
3767         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3768         assert_eq!(events_1.len(), 1);
3769         match events_1[0] {
3770                 MessageSendEvent::UpdateHTLCs { .. } => {},
3771                 _ => panic!("Unexpected event"),
3772         }
3773
3774         assert!(nodes[1].node.claim_funds(payment_preimage_1));
3775         check_added_monitors!(nodes[1], 1);
3776
3777         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3778         assert_eq!(events_2.len(), 1);
3779         match events_2[0] {
3780                 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 } } => {
3781                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3782                         assert!(update_add_htlcs.is_empty());
3783                         assert_eq!(update_fulfill_htlcs.len(), 1);
3784                         assert!(update_fail_htlcs.is_empty());
3785                         assert!(update_fail_malformed_htlcs.is_empty());
3786                         assert!(update_fee.is_none());
3787
3788                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3789                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3790                         assert_eq!(events_3.len(), 1);
3791                         match events_3[0] {
3792                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3793                                         assert_eq!(*payment_preimage, payment_preimage_1);
3794                                         assert_eq!(*payment_hash, payment_hash_1);
3795                                 },
3796                                 _ => panic!("Unexpected event"),
3797                         }
3798
3799                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3800                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3801                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3802                         check_added_monitors!(nodes[0], 1);
3803                 },
3804                 _ => panic!("Unexpected event"),
3805         }
3806
3807         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3808         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3809
3810         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3811         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3812         assert_eq!(reestablish_1.len(), 1);
3813         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3814         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3815         assert_eq!(reestablish_2.len(), 1);
3816
3817         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3818         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3819         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3820         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3821
3822         assert!(as_resp.0.is_none());
3823         assert!(bs_resp.0.is_none());
3824
3825         assert!(bs_resp.1.is_none());
3826         assert!(bs_resp.2.is_none());
3827
3828         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3829
3830         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3831         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3832         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3833         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3834         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3835         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3836         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3837         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3838         // No commitment_signed so get_event_msg's assert(len == 1) passes
3839         check_added_monitors!(nodes[1], 1);
3840
3841         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3842         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3843         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3844         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3845         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3846         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3847         assert!(bs_second_commitment_signed.update_fee.is_none());
3848         check_added_monitors!(nodes[1], 1);
3849
3850         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3851         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3852         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3853         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3854         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3855         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3856         assert!(as_commitment_signed.update_fee.is_none());
3857         check_added_monitors!(nodes[0], 1);
3858
3859         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3860         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3861         // No commitment_signed so get_event_msg's assert(len == 1) passes
3862         check_added_monitors!(nodes[0], 1);
3863
3864         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3865         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3866         // No commitment_signed so get_event_msg's assert(len == 1) passes
3867         check_added_monitors!(nodes[1], 1);
3868
3869         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3870         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3871         check_added_monitors!(nodes[1], 1);
3872
3873         expect_pending_htlcs_forwardable!(nodes[1]);
3874
3875         let events_5 = nodes[1].node.get_and_clear_pending_events();
3876         assert_eq!(events_5.len(), 1);
3877         match events_5[0] {
3878                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
3879                         assert_eq!(payment_hash_2, *payment_hash);
3880                         match &purpose {
3881                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3882                                         assert!(payment_preimage.is_none());
3883                                         assert_eq!(payment_secret_2, *payment_secret);
3884                                 },
3885                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3886                         }
3887                 },
3888                 _ => panic!("Unexpected event"),
3889         }
3890
3891         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3892         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3893         check_added_monitors!(nodes[0], 1);
3894
3895         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3896 }
3897
3898 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3899         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3900         // to avoid our counterparty failing the channel.
3901         let chanmon_cfgs = create_chanmon_cfgs(2);
3902         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3903         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3904         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3905
3906         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3907
3908         let our_payment_hash = if send_partial_mpp {
3909                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
3910                 // Use the utility function send_payment_along_path to send the payment with MPP data which
3911                 // indicates there are more HTLCs coming.
3912                 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.
3913                 let payment_id = PaymentId([42; 32]);
3914                 nodes[0].node.send_payment_along_path(&route.paths[0], &route.payee, &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
3915                 check_added_monitors!(nodes[0], 1);
3916                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3917                 assert_eq!(events.len(), 1);
3918                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3919                 // hop should *not* yet generate any PaymentReceived event(s).
3920                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
3921                 our_payment_hash
3922         } else {
3923                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3924         };
3925
3926         let mut block = Block {
3927                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3928                 txdata: vec![],
3929         };
3930         connect_block(&nodes[0], &block);
3931         connect_block(&nodes[1], &block);
3932         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
3933         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
3934                 block.header.prev_blockhash = block.block_hash();
3935                 connect_block(&nodes[0], &block);
3936                 connect_block(&nodes[1], &block);
3937         }
3938
3939         expect_pending_htlcs_forwardable!(nodes[1]);
3940
3941         check_added_monitors!(nodes[1], 1);
3942         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3943         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3944         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3945         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3946         assert!(htlc_timeout_updates.update_fee.is_none());
3947
3948         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3949         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3950         // 100_000 msat as u64, followed by the height at which we failed back above
3951         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3952         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
3953         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
3954 }
3955
3956 #[test]
3957 fn test_htlc_timeout() {
3958         do_test_htlc_timeout(true);
3959         do_test_htlc_timeout(false);
3960 }
3961
3962 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
3963         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
3964         let chanmon_cfgs = create_chanmon_cfgs(3);
3965         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3966         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3967         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3968         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3969         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3970
3971         // Make sure all nodes are at the same starting height
3972         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
3973         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
3974         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
3975
3976         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
3977         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
3978         {
3979                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
3980         }
3981         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
3982         check_added_monitors!(nodes[1], 1);
3983
3984         // Now attempt to route a second payment, which should be placed in the holding cell
3985         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
3986         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
3987         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
3988         if forwarded_htlc {
3989                 check_added_monitors!(nodes[0], 1);
3990                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
3991                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3992                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3993                 expect_pending_htlcs_forwardable!(nodes[1]);
3994         }
3995         check_added_monitors!(nodes[1], 0);
3996
3997         connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
3998         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3999         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4000         connect_blocks(&nodes[1], 1);
4001
4002         if forwarded_htlc {
4003                 expect_pending_htlcs_forwardable!(nodes[1]);
4004                 check_added_monitors!(nodes[1], 1);
4005                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4006                 assert_eq!(fail_commit.len(), 1);
4007                 match fail_commit[0] {
4008                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4009                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4010                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4011                         },
4012                         _ => unreachable!(),
4013                 }
4014                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4015         } else {
4016                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4017         }
4018 }
4019
4020 #[test]
4021 fn test_holding_cell_htlc_add_timeouts() {
4022         do_test_holding_cell_htlc_add_timeouts(false);
4023         do_test_holding_cell_htlc_add_timeouts(true);
4024 }
4025
4026 #[test]
4027 fn test_no_txn_manager_serialize_deserialize() {
4028         let chanmon_cfgs = create_chanmon_cfgs(2);
4029         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4030         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4031         let logger: test_utils::TestLogger;
4032         let fee_estimator: test_utils::TestFeeEstimator;
4033         let persister: test_utils::TestPersister;
4034         let new_chain_monitor: test_utils::TestChainMonitor;
4035         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4036         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4037
4038         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4039
4040         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4041
4042         let nodes_0_serialized = nodes[0].node.encode();
4043         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4044         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4045                 .write(&mut chan_0_monitor_serialized).unwrap();
4046
4047         logger = test_utils::TestLogger::new();
4048         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4049         persister = test_utils::TestPersister::new();
4050         let keys_manager = &chanmon_cfgs[0].keys_manager;
4051         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4052         nodes[0].chain_monitor = &new_chain_monitor;
4053         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4054         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4055                 &mut chan_0_monitor_read, keys_manager).unwrap();
4056         assert!(chan_0_monitor_read.is_empty());
4057
4058         let mut nodes_0_read = &nodes_0_serialized[..];
4059         let config = UserConfig::default();
4060         let (_, nodes_0_deserialized_tmp) = {
4061                 let mut channel_monitors = HashMap::new();
4062                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4063                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4064                         default_config: config,
4065                         keys_manager,
4066                         fee_estimator: &fee_estimator,
4067                         chain_monitor: nodes[0].chain_monitor,
4068                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4069                         logger: &logger,
4070                         channel_monitors,
4071                 }).unwrap()
4072         };
4073         nodes_0_deserialized = nodes_0_deserialized_tmp;
4074         assert!(nodes_0_read.is_empty());
4075
4076         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4077         nodes[0].node = &nodes_0_deserialized;
4078         assert_eq!(nodes[0].node.list_channels().len(), 1);
4079         check_added_monitors!(nodes[0], 1);
4080
4081         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4082         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4083         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4084         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4085
4086         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4087         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4088         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4089         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4090
4091         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4092         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4093         for node in nodes.iter() {
4094                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4095                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4096                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4097         }
4098
4099         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4100 }
4101
4102 #[test]
4103 fn test_manager_serialize_deserialize_events() {
4104         // This test makes sure the events field in ChannelManager survives de/serialization
4105         let chanmon_cfgs = create_chanmon_cfgs(2);
4106         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4107         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4108         let fee_estimator: test_utils::TestFeeEstimator;
4109         let persister: test_utils::TestPersister;
4110         let logger: test_utils::TestLogger;
4111         let new_chain_monitor: test_utils::TestChainMonitor;
4112         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4113         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4114
4115         // Start creating a channel, but stop right before broadcasting the funding transaction
4116         let channel_value = 100000;
4117         let push_msat = 10001;
4118         let a_flags = InitFeatures::known();
4119         let b_flags = InitFeatures::known();
4120         let node_a = nodes.remove(0);
4121         let node_b = nodes.remove(0);
4122         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4123         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()));
4124         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()));
4125
4126         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4127
4128         node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4129         check_added_monitors!(node_a, 0);
4130
4131         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()));
4132         {
4133                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4134                 assert_eq!(added_monitors.len(), 1);
4135                 assert_eq!(added_monitors[0].0, funding_output);
4136                 added_monitors.clear();
4137         }
4138
4139         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4140         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4141         {
4142                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4143                 assert_eq!(added_monitors.len(), 1);
4144                 assert_eq!(added_monitors[0].0, funding_output);
4145                 added_monitors.clear();
4146         }
4147         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4148
4149         nodes.push(node_a);
4150         nodes.push(node_b);
4151
4152         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4153         let nodes_0_serialized = nodes[0].node.encode();
4154         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4155         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4156
4157         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4158         logger = test_utils::TestLogger::new();
4159         persister = test_utils::TestPersister::new();
4160         let keys_manager = &chanmon_cfgs[0].keys_manager;
4161         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4162         nodes[0].chain_monitor = &new_chain_monitor;
4163         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4164         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4165                 &mut chan_0_monitor_read, keys_manager).unwrap();
4166         assert!(chan_0_monitor_read.is_empty());
4167
4168         let mut nodes_0_read = &nodes_0_serialized[..];
4169         let config = UserConfig::default();
4170         let (_, nodes_0_deserialized_tmp) = {
4171                 let mut channel_monitors = HashMap::new();
4172                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4173                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4174                         default_config: config,
4175                         keys_manager,
4176                         fee_estimator: &fee_estimator,
4177                         chain_monitor: nodes[0].chain_monitor,
4178                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4179                         logger: &logger,
4180                         channel_monitors,
4181                 }).unwrap()
4182         };
4183         nodes_0_deserialized = nodes_0_deserialized_tmp;
4184         assert!(nodes_0_read.is_empty());
4185
4186         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4187
4188         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4189         nodes[0].node = &nodes_0_deserialized;
4190
4191         // After deserializing, make sure the funding_transaction is still held by the channel manager
4192         let events_4 = nodes[0].node.get_and_clear_pending_events();
4193         assert_eq!(events_4.len(), 0);
4194         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4195         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4196
4197         // Make sure the channel is functioning as though the de/serialization never happened
4198         assert_eq!(nodes[0].node.list_channels().len(), 1);
4199         check_added_monitors!(nodes[0], 1);
4200
4201         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4202         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4203         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4204         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4205
4206         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4207         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4208         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4209         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4210
4211         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4212         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4213         for node in nodes.iter() {
4214                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4215                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4216                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4217         }
4218
4219         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4220 }
4221
4222 #[test]
4223 fn test_simple_manager_serialize_deserialize() {
4224         let chanmon_cfgs = create_chanmon_cfgs(2);
4225         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4226         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4227         let logger: test_utils::TestLogger;
4228         let fee_estimator: test_utils::TestFeeEstimator;
4229         let persister: test_utils::TestPersister;
4230         let new_chain_monitor: test_utils::TestChainMonitor;
4231         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4232         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4233         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4234
4235         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4236         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4237
4238         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4239
4240         let nodes_0_serialized = nodes[0].node.encode();
4241         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4242         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4243
4244         logger = test_utils::TestLogger::new();
4245         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4246         persister = test_utils::TestPersister::new();
4247         let keys_manager = &chanmon_cfgs[0].keys_manager;
4248         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4249         nodes[0].chain_monitor = &new_chain_monitor;
4250         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4251         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4252                 &mut chan_0_monitor_read, keys_manager).unwrap();
4253         assert!(chan_0_monitor_read.is_empty());
4254
4255         let mut nodes_0_read = &nodes_0_serialized[..];
4256         let (_, nodes_0_deserialized_tmp) = {
4257                 let mut channel_monitors = HashMap::new();
4258                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4259                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4260                         default_config: UserConfig::default(),
4261                         keys_manager,
4262                         fee_estimator: &fee_estimator,
4263                         chain_monitor: nodes[0].chain_monitor,
4264                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4265                         logger: &logger,
4266                         channel_monitors,
4267                 }).unwrap()
4268         };
4269         nodes_0_deserialized = nodes_0_deserialized_tmp;
4270         assert!(nodes_0_read.is_empty());
4271
4272         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4273         nodes[0].node = &nodes_0_deserialized;
4274         check_added_monitors!(nodes[0], 1);
4275
4276         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4277
4278         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4279         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4280 }
4281
4282 #[test]
4283 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4284         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4285         let chanmon_cfgs = create_chanmon_cfgs(4);
4286         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4287         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4288         let logger: test_utils::TestLogger;
4289         let fee_estimator: test_utils::TestFeeEstimator;
4290         let persister: test_utils::TestPersister;
4291         let new_chain_monitor: test_utils::TestChainMonitor;
4292         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4293         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4294         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4295         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4296         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4297
4298         let mut node_0_stale_monitors_serialized = Vec::new();
4299         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4300                 let mut writer = test_utils::TestVecWriter(Vec::new());
4301                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4302                 node_0_stale_monitors_serialized.push(writer.0);
4303         }
4304
4305         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4306
4307         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4308         let nodes_0_serialized = nodes[0].node.encode();
4309
4310         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4311         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4312         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4313         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4314
4315         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4316         // nodes[3])
4317         let mut node_0_monitors_serialized = Vec::new();
4318         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4319                 let mut writer = test_utils::TestVecWriter(Vec::new());
4320                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4321                 node_0_monitors_serialized.push(writer.0);
4322         }
4323
4324         logger = test_utils::TestLogger::new();
4325         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4326         persister = test_utils::TestPersister::new();
4327         let keys_manager = &chanmon_cfgs[0].keys_manager;
4328         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4329         nodes[0].chain_monitor = &new_chain_monitor;
4330
4331
4332         let mut node_0_stale_monitors = Vec::new();
4333         for serialized in node_0_stale_monitors_serialized.iter() {
4334                 let mut read = &serialized[..];
4335                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4336                 assert!(read.is_empty());
4337                 node_0_stale_monitors.push(monitor);
4338         }
4339
4340         let mut node_0_monitors = Vec::new();
4341         for serialized in node_0_monitors_serialized.iter() {
4342                 let mut read = &serialized[..];
4343                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4344                 assert!(read.is_empty());
4345                 node_0_monitors.push(monitor);
4346         }
4347
4348         let mut nodes_0_read = &nodes_0_serialized[..];
4349         if let Err(msgs::DecodeError::InvalidValue) =
4350                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4351                 default_config: UserConfig::default(),
4352                 keys_manager,
4353                 fee_estimator: &fee_estimator,
4354                 chain_monitor: nodes[0].chain_monitor,
4355                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4356                 logger: &logger,
4357                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4358         }) { } else {
4359                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4360         };
4361
4362         let mut nodes_0_read = &nodes_0_serialized[..];
4363         let (_, nodes_0_deserialized_tmp) =
4364                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4365                 default_config: UserConfig::default(),
4366                 keys_manager,
4367                 fee_estimator: &fee_estimator,
4368                 chain_monitor: nodes[0].chain_monitor,
4369                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4370                 logger: &logger,
4371                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4372         }).unwrap();
4373         nodes_0_deserialized = nodes_0_deserialized_tmp;
4374         assert!(nodes_0_read.is_empty());
4375
4376         { // Channel close should result in a commitment tx
4377                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4378                 assert_eq!(txn.len(), 1);
4379                 check_spends!(txn[0], funding_tx);
4380                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4381         }
4382
4383         for monitor in node_0_monitors.drain(..) {
4384                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4385                 check_added_monitors!(nodes[0], 1);
4386         }
4387         nodes[0].node = &nodes_0_deserialized;
4388         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4389
4390         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4391         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4392         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4393         //... and we can even still claim the payment!
4394         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4395
4396         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4397         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4398         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4399         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4400         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4401         assert_eq!(msg_events.len(), 1);
4402         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4403                 match action {
4404                         &ErrorAction::SendErrorMessage { ref msg } => {
4405                                 assert_eq!(msg.channel_id, channel_id);
4406                         },
4407                         _ => panic!("Unexpected event!"),
4408                 }
4409         }
4410 }
4411
4412 macro_rules! check_spendable_outputs {
4413         ($node: expr, $keysinterface: expr) => {
4414                 {
4415                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4416                         let mut txn = Vec::new();
4417                         let mut all_outputs = Vec::new();
4418                         let secp_ctx = Secp256k1::new();
4419                         for event in events.drain(..) {
4420                                 match event {
4421                                         Event::SpendableOutputs { mut outputs } => {
4422                                                 for outp in outputs.drain(..) {
4423                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4424                                                         all_outputs.push(outp);
4425                                                 }
4426                                         },
4427                                         _ => panic!("Unexpected event"),
4428                                 };
4429                         }
4430                         if all_outputs.len() > 1 {
4431                                 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) {
4432                                         txn.push(tx);
4433                                 }
4434                         }
4435                         txn
4436                 }
4437         }
4438 }
4439
4440 #[test]
4441 fn test_claim_sizeable_push_msat() {
4442         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4443         let chanmon_cfgs = create_chanmon_cfgs(2);
4444         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4445         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4446         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4447
4448         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4449         nodes[1].node.force_close_channel(&chan.2).unwrap();
4450         check_closed_broadcast!(nodes[1], true);
4451         check_added_monitors!(nodes[1], 1);
4452         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4453         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4454         assert_eq!(node_txn.len(), 1);
4455         check_spends!(node_txn[0], chan.3);
4456         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
4457
4458         mine_transaction(&nodes[1], &node_txn[0]);
4459         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4460
4461         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4462         assert_eq!(spend_txn.len(), 1);
4463         assert_eq!(spend_txn[0].input.len(), 1);
4464         check_spends!(spend_txn[0], node_txn[0]);
4465         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4466 }
4467
4468 #[test]
4469 fn test_claim_on_remote_sizeable_push_msat() {
4470         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4471         // to_remote output is encumbered by a P2WPKH
4472         let chanmon_cfgs = create_chanmon_cfgs(2);
4473         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4474         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4475         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4476
4477         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4478         nodes[0].node.force_close_channel(&chan.2).unwrap();
4479         check_closed_broadcast!(nodes[0], true);
4480         check_added_monitors!(nodes[0], 1);
4481         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4482
4483         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4484         assert_eq!(node_txn.len(), 1);
4485         check_spends!(node_txn[0], chan.3);
4486         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
4487
4488         mine_transaction(&nodes[1], &node_txn[0]);
4489         check_closed_broadcast!(nodes[1], true);
4490         check_added_monitors!(nodes[1], 1);
4491         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4492         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4493
4494         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4495         assert_eq!(spend_txn.len(), 1);
4496         check_spends!(spend_txn[0], node_txn[0]);
4497 }
4498
4499 #[test]
4500 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4501         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4502         // to_remote output is encumbered by a P2WPKH
4503
4504         let chanmon_cfgs = create_chanmon_cfgs(2);
4505         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4506         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4507         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4508
4509         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4510         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4511         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4512         assert_eq!(revoked_local_txn[0].input.len(), 1);
4513         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4514
4515         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4516         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4517         check_closed_broadcast!(nodes[1], true);
4518         check_added_monitors!(nodes[1], 1);
4519         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4520
4521         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4522         mine_transaction(&nodes[1], &node_txn[0]);
4523         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4524
4525         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4526         assert_eq!(spend_txn.len(), 3);
4527         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4528         check_spends!(spend_txn[1], node_txn[0]);
4529         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4530 }
4531
4532 #[test]
4533 fn test_static_spendable_outputs_preimage_tx() {
4534         let chanmon_cfgs = create_chanmon_cfgs(2);
4535         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4536         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4537         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4538
4539         // Create some initial channels
4540         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4541
4542         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4543
4544         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4545         assert_eq!(commitment_tx[0].input.len(), 1);
4546         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4547
4548         // Settle A's commitment tx on B's chain
4549         assert!(nodes[1].node.claim_funds(payment_preimage));
4550         check_added_monitors!(nodes[1], 1);
4551         mine_transaction(&nodes[1], &commitment_tx[0]);
4552         check_added_monitors!(nodes[1], 1);
4553         let events = nodes[1].node.get_and_clear_pending_msg_events();
4554         match events[0] {
4555                 MessageSendEvent::UpdateHTLCs { .. } => {},
4556                 _ => panic!("Unexpected event"),
4557         }
4558         match events[1] {
4559                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4560                 _ => panic!("Unexepected event"),
4561         }
4562
4563         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4564         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4565         assert_eq!(node_txn.len(), 3);
4566         check_spends!(node_txn[0], commitment_tx[0]);
4567         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4568         check_spends!(node_txn[1], chan_1.3);
4569         check_spends!(node_txn[2], node_txn[1]);
4570
4571         mine_transaction(&nodes[1], &node_txn[0]);
4572         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4573         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4574
4575         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4576         assert_eq!(spend_txn.len(), 1);
4577         check_spends!(spend_txn[0], node_txn[0]);
4578 }
4579
4580 #[test]
4581 fn test_static_spendable_outputs_timeout_tx() {
4582         let chanmon_cfgs = create_chanmon_cfgs(2);
4583         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4584         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4585         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4586
4587         // Create some initial channels
4588         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4589
4590         // Rebalance the network a bit by relaying one payment through all the channels ...
4591         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4592
4593         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4594
4595         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4596         assert_eq!(commitment_tx[0].input.len(), 1);
4597         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4598
4599         // Settle A's commitment tx on B' chain
4600         mine_transaction(&nodes[1], &commitment_tx[0]);
4601         check_added_monitors!(nodes[1], 1);
4602         let events = nodes[1].node.get_and_clear_pending_msg_events();
4603         match events[0] {
4604                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4605                 _ => panic!("Unexpected event"),
4606         }
4607         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4608
4609         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4610         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4611         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4612         check_spends!(node_txn[0], chan_1.3.clone());
4613         check_spends!(node_txn[1],  commitment_tx[0].clone());
4614         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4615
4616         mine_transaction(&nodes[1], &node_txn[1]);
4617         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4618         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4619         expect_payment_failed!(nodes[1], our_payment_hash, true);
4620
4621         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4622         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4623         check_spends!(spend_txn[0], commitment_tx[0]);
4624         check_spends!(spend_txn[1], node_txn[1]);
4625         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4626 }
4627
4628 #[test]
4629 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4630         let chanmon_cfgs = create_chanmon_cfgs(2);
4631         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4632         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4633         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4634
4635         // Create some initial channels
4636         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4637
4638         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4639         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4640         assert_eq!(revoked_local_txn[0].input.len(), 1);
4641         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4642
4643         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4644
4645         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4646         check_closed_broadcast!(nodes[1], true);
4647         check_added_monitors!(nodes[1], 1);
4648         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4649
4650         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4651         assert_eq!(node_txn.len(), 2);
4652         assert_eq!(node_txn[0].input.len(), 2);
4653         check_spends!(node_txn[0], revoked_local_txn[0]);
4654
4655         mine_transaction(&nodes[1], &node_txn[0]);
4656         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4657
4658         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4659         assert_eq!(spend_txn.len(), 1);
4660         check_spends!(spend_txn[0], node_txn[0]);
4661 }
4662
4663 #[test]
4664 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4665         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4666         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4667         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4668         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4669         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4670
4671         // Create some initial channels
4672         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4673
4674         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4675         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4676         assert_eq!(revoked_local_txn[0].input.len(), 1);
4677         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4678
4679         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4680
4681         // A will generate HTLC-Timeout from revoked commitment tx
4682         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4683         check_closed_broadcast!(nodes[0], true);
4684         check_added_monitors!(nodes[0], 1);
4685         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4686         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4687
4688         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4689         assert_eq!(revoked_htlc_txn.len(), 2);
4690         check_spends!(revoked_htlc_txn[0], chan_1.3);
4691         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4692         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4693         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4694         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4695
4696         // B will generate justice tx from A's revoked commitment/HTLC tx
4697         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4698         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4699         check_closed_broadcast!(nodes[1], true);
4700         check_added_monitors!(nodes[1], 1);
4701         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4702
4703         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4704         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4705         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4706         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4707         // transactions next...
4708         assert_eq!(node_txn[0].input.len(), 3);
4709         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4710
4711         assert_eq!(node_txn[1].input.len(), 2);
4712         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4713         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4714                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4715         } else {
4716                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4717                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4718         }
4719
4720         assert_eq!(node_txn[2].input.len(), 1);
4721         check_spends!(node_txn[2], chan_1.3);
4722
4723         mine_transaction(&nodes[1], &node_txn[1]);
4724         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4725
4726         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4727         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4728         assert_eq!(spend_txn.len(), 1);
4729         assert_eq!(spend_txn[0].input.len(), 1);
4730         check_spends!(spend_txn[0], node_txn[1]);
4731 }
4732
4733 #[test]
4734 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4735         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4736         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4737         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4738         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4739         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4740
4741         // Create some initial channels
4742         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4743
4744         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4745         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4746         assert_eq!(revoked_local_txn[0].input.len(), 1);
4747         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4748
4749         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4750         assert_eq!(revoked_local_txn[0].output.len(), 2);
4751
4752         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4753
4754         // B will generate HTLC-Success from revoked commitment tx
4755         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4756         check_closed_broadcast!(nodes[1], true);
4757         check_added_monitors!(nodes[1], 1);
4758         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4759         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4760
4761         assert_eq!(revoked_htlc_txn.len(), 2);
4762         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4763         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4764         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4765
4766         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4767         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4768         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4769
4770         // A will generate justice tx from B's revoked commitment/HTLC tx
4771         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4772         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4773         check_closed_broadcast!(nodes[0], true);
4774         check_added_monitors!(nodes[0], 1);
4775         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4776
4777         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4778         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4779
4780         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4781         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4782         // transactions next...
4783         assert_eq!(node_txn[0].input.len(), 2);
4784         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4785         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4786                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4787         } else {
4788                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4789                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4790         }
4791
4792         assert_eq!(node_txn[1].input.len(), 1);
4793         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4794
4795         check_spends!(node_txn[2], chan_1.3);
4796
4797         mine_transaction(&nodes[0], &node_txn[1]);
4798         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4799
4800         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4801         // didn't try to generate any new transactions.
4802
4803         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4804         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4805         assert_eq!(spend_txn.len(), 3);
4806         assert_eq!(spend_txn[0].input.len(), 1);
4807         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4808         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4809         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4810         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4811 }
4812
4813 #[test]
4814 fn test_onchain_to_onchain_claim() {
4815         // Test that in case of channel closure, we detect the state of output and claim HTLC
4816         // on downstream peer's remote commitment tx.
4817         // First, have C claim an HTLC against its own latest commitment transaction.
4818         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4819         // channel.
4820         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4821         // gets broadcast.
4822
4823         let chanmon_cfgs = create_chanmon_cfgs(3);
4824         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4825         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4826         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4827
4828         // Create some initial channels
4829         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4830         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4831
4832         // Ensure all nodes are at the same height
4833         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4834         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4835         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4836         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4837
4838         // Rebalance the network a bit by relaying one payment through all the channels ...
4839         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4840         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4841
4842         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4843         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4844         check_spends!(commitment_tx[0], chan_2.3);
4845         nodes[2].node.claim_funds(payment_preimage);
4846         check_added_monitors!(nodes[2], 1);
4847         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4848         assert!(updates.update_add_htlcs.is_empty());
4849         assert!(updates.update_fail_htlcs.is_empty());
4850         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4851         assert!(updates.update_fail_malformed_htlcs.is_empty());
4852
4853         mine_transaction(&nodes[2], &commitment_tx[0]);
4854         check_closed_broadcast!(nodes[2], true);
4855         check_added_monitors!(nodes[2], 1);
4856         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4857
4858         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4859         assert_eq!(c_txn.len(), 3);
4860         assert_eq!(c_txn[0], c_txn[2]);
4861         assert_eq!(commitment_tx[0], c_txn[1]);
4862         check_spends!(c_txn[1], chan_2.3);
4863         check_spends!(c_txn[2], c_txn[1]);
4864         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4865         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4866         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4867         assert_eq!(c_txn[0].lock_time, 0); // Success tx
4868
4869         // 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
4870         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4871         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
4872         check_added_monitors!(nodes[1], 1);
4873         let events = nodes[1].node.get_and_clear_pending_events();
4874         assert_eq!(events.len(), 2);
4875         match events[0] {
4876                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4877                 _ => panic!("Unexpected event"),
4878         }
4879         match events[1] {
4880                 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
4881                         assert_eq!(fee_earned_msat, Some(1000));
4882                         assert_eq!(claim_from_onchain_tx, true);
4883                 },
4884                 _ => panic!("Unexpected event"),
4885         }
4886         {
4887                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4888                 // ChannelMonitor: claim tx
4889                 assert_eq!(b_txn.len(), 1);
4890                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
4891                 b_txn.clear();
4892         }
4893         check_added_monitors!(nodes[1], 1);
4894         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4895         assert_eq!(msg_events.len(), 3);
4896         match msg_events[0] {
4897                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4898                 _ => panic!("Unexpected event"),
4899         }
4900         match msg_events[1] {
4901                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4902                 _ => panic!("Unexpected event"),
4903         }
4904         match msg_events[2] {
4905                 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, .. } } => {
4906                         assert!(update_add_htlcs.is_empty());
4907                         assert!(update_fail_htlcs.is_empty());
4908                         assert_eq!(update_fulfill_htlcs.len(), 1);
4909                         assert!(update_fail_malformed_htlcs.is_empty());
4910                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4911                 },
4912                 _ => panic!("Unexpected event"),
4913         };
4914         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4915         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4916         mine_transaction(&nodes[1], &commitment_tx[0]);
4917         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4918         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4919         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4920         assert_eq!(b_txn.len(), 3);
4921         check_spends!(b_txn[1], chan_1.3);
4922         check_spends!(b_txn[2], b_txn[1]);
4923         check_spends!(b_txn[0], commitment_tx[0]);
4924         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4925         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4926         assert_eq!(b_txn[0].lock_time, 0); // Success tx
4927
4928         check_closed_broadcast!(nodes[1], true);
4929         check_added_monitors!(nodes[1], 1);
4930 }
4931
4932 #[test]
4933 fn test_duplicate_payment_hash_one_failure_one_success() {
4934         // Topology : A --> B --> C --> D
4935         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4936         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4937         // we forward one of the payments onwards to D.
4938         let chanmon_cfgs = create_chanmon_cfgs(4);
4939         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4940         // When this test was written, the default base fee floated based on the HTLC count.
4941         // It is now fixed, so we simply set the fee to the expected value here.
4942         let mut config = test_default_channel_config();
4943         config.channel_options.forwarding_fee_base_msat = 196;
4944         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4945                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4946         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4947
4948         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4949         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4950         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
4951
4952         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4953         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4954         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4955         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4956         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4957
4958         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
4959
4960         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, 0).unwrap();
4961         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4962         // script push size limit so that the below script length checks match
4963         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4964         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], vec![], 900000, TEST_FINAL_CLTV - 40);
4965         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
4966
4967         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4968         assert_eq!(commitment_txn[0].input.len(), 1);
4969         check_spends!(commitment_txn[0], chan_2.3);
4970
4971         mine_transaction(&nodes[1], &commitment_txn[0]);
4972         check_closed_broadcast!(nodes[1], true);
4973         check_added_monitors!(nodes[1], 1);
4974         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4975         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4976
4977         let htlc_timeout_tx;
4978         { // Extract one of the two HTLC-Timeout transaction
4979                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4980                 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
4981                 assert_eq!(node_txn.len(), 4);
4982                 check_spends!(node_txn[0], chan_2.3);
4983
4984                 check_spends!(node_txn[1], commitment_txn[0]);
4985                 assert_eq!(node_txn[1].input.len(), 1);
4986                 check_spends!(node_txn[2], commitment_txn[0]);
4987                 assert_eq!(node_txn[2].input.len(), 1);
4988                 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
4989                 check_spends!(node_txn[3], commitment_txn[0]);
4990                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
4991
4992                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4993                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4994                 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4995                 htlc_timeout_tx = node_txn[1].clone();
4996         }
4997
4998         nodes[2].node.claim_funds(our_payment_preimage);
4999         mine_transaction(&nodes[2], &commitment_txn[0]);
5000         check_added_monitors!(nodes[2], 2);
5001         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5002         let events = nodes[2].node.get_and_clear_pending_msg_events();
5003         match events[0] {
5004                 MessageSendEvent::UpdateHTLCs { .. } => {},
5005                 _ => panic!("Unexpected event"),
5006         }
5007         match events[1] {
5008                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5009                 _ => panic!("Unexepected event"),
5010         }
5011         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5012         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)
5013         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5014         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5015         assert_eq!(htlc_success_txn[0].input.len(), 1);
5016         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5017         assert_eq!(htlc_success_txn[1].input.len(), 1);
5018         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5019         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5020         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5021         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5022         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5023         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5024
5025         mine_transaction(&nodes[1], &htlc_timeout_tx);
5026         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5027         expect_pending_htlcs_forwardable!(nodes[1]);
5028         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5029         assert!(htlc_updates.update_add_htlcs.is_empty());
5030         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5031         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5032         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5033         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5034         check_added_monitors!(nodes[1], 1);
5035
5036         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5037         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5038         {
5039                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5040         }
5041         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5042
5043         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5044         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5045         // and nodes[2] fee) is rounded down and then claimed in full.
5046         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5047         expect_payment_forwarded!(nodes[1], Some(196*2), true);
5048         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5049         assert!(updates.update_add_htlcs.is_empty());
5050         assert!(updates.update_fail_htlcs.is_empty());
5051         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5052         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5053         assert!(updates.update_fail_malformed_htlcs.is_empty());
5054         check_added_monitors!(nodes[1], 1);
5055
5056         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5057         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5058
5059         let events = nodes[0].node.get_and_clear_pending_events();
5060         match events[0] {
5061                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5062                         assert_eq!(*payment_preimage, our_payment_preimage);
5063                         assert_eq!(*payment_hash, duplicate_payment_hash);
5064                 }
5065                 _ => panic!("Unexpected event"),
5066         }
5067 }
5068
5069 #[test]
5070 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5071         let chanmon_cfgs = create_chanmon_cfgs(2);
5072         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5073         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5074         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5075
5076         // Create some initial channels
5077         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5078
5079         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5080         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5081         assert_eq!(local_txn.len(), 1);
5082         assert_eq!(local_txn[0].input.len(), 1);
5083         check_spends!(local_txn[0], chan_1.3);
5084
5085         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5086         nodes[1].node.claim_funds(payment_preimage);
5087         check_added_monitors!(nodes[1], 1);
5088         mine_transaction(&nodes[1], &local_txn[0]);
5089         check_added_monitors!(nodes[1], 1);
5090         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5091         let events = nodes[1].node.get_and_clear_pending_msg_events();
5092         match events[0] {
5093                 MessageSendEvent::UpdateHTLCs { .. } => {},
5094                 _ => panic!("Unexpected event"),
5095         }
5096         match events[1] {
5097                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5098                 _ => panic!("Unexepected event"),
5099         }
5100         let node_tx = {
5101                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5102                 assert_eq!(node_txn.len(), 3);
5103                 assert_eq!(node_txn[0], node_txn[2]);
5104                 assert_eq!(node_txn[1], local_txn[0]);
5105                 assert_eq!(node_txn[0].input.len(), 1);
5106                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5107                 check_spends!(node_txn[0], local_txn[0]);
5108                 node_txn[0].clone()
5109         };
5110
5111         mine_transaction(&nodes[1], &node_tx);
5112         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5113
5114         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5115         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5116         assert_eq!(spend_txn.len(), 1);
5117         assert_eq!(spend_txn[0].input.len(), 1);
5118         check_spends!(spend_txn[0], node_tx);
5119         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5120 }
5121
5122 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5123         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5124         // unrevoked commitment transaction.
5125         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5126         // a remote RAA before they could be failed backwards (and combinations thereof).
5127         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5128         // use the same payment hashes.
5129         // Thus, we use a six-node network:
5130         //
5131         // A \         / E
5132         //    - C - D -
5133         // B /         \ F
5134         // And test where C fails back to A/B when D announces its latest commitment transaction
5135         let chanmon_cfgs = create_chanmon_cfgs(6);
5136         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5137         // When this test was written, the default base fee floated based on the HTLC count.
5138         // It is now fixed, so we simply set the fee to the expected value here.
5139         let mut config = test_default_channel_config();
5140         config.channel_options.forwarding_fee_base_msat = 196;
5141         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5142                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5143         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5144
5145         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5146         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5147         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5148         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5149         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5150
5151         // Rebalance and check output sanity...
5152         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5153         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5154         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5155
5156         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5157         // 0th HTLC:
5158         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
5159         // 1st HTLC:
5160         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
5161         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5162         // 2nd HTLC:
5163         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, 0).unwrap()); // not added < dust limit + HTLC tx fee
5164         // 3rd HTLC:
5165         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, 0).unwrap()); // not added < dust limit + HTLC tx fee
5166         // 4th HTLC:
5167         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5168         // 5th HTLC:
5169         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5170         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5171         // 6th HTLC:
5172         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, 0).unwrap());
5173         // 7th HTLC:
5174         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, 0).unwrap());
5175
5176         // 8th HTLC:
5177         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5178         // 9th HTLC:
5179         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5180         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, 0).unwrap()); // not added < dust limit + HTLC tx fee
5181
5182         // 10th HTLC:
5183         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
5184         // 11th HTLC:
5185         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5186         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, 0).unwrap());
5187
5188         // Double-check that six of the new HTLC were added
5189         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5190         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5191         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5192         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5193
5194         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5195         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5196         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5197         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5198         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5199         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5200         check_added_monitors!(nodes[4], 0);
5201         expect_pending_htlcs_forwardable!(nodes[4]);
5202         check_added_monitors!(nodes[4], 1);
5203
5204         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5205         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5206         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5207         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5208         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5209         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5210
5211         // Fail 3rd below-dust and 7th above-dust HTLCs
5212         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5213         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5214         check_added_monitors!(nodes[5], 0);
5215         expect_pending_htlcs_forwardable!(nodes[5]);
5216         check_added_monitors!(nodes[5], 1);
5217
5218         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5219         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5220         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5221         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5222
5223         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5224
5225         expect_pending_htlcs_forwardable!(nodes[3]);
5226         check_added_monitors!(nodes[3], 1);
5227         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5228         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5229         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5230         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5231         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5232         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5233         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5234         if deliver_last_raa {
5235                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5236         } else {
5237                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5238         }
5239
5240         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5241         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5242         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5243         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5244         //
5245         // We now broadcast the latest commitment transaction, which *should* result in failures for
5246         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5247         // the non-broadcast above-dust HTLCs.
5248         //
5249         // Alternatively, we may broadcast the previous commitment transaction, which should only
5250         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5251         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5252
5253         if announce_latest {
5254                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5255         } else {
5256                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5257         }
5258         let events = nodes[2].node.get_and_clear_pending_events();
5259         let close_event = if deliver_last_raa {
5260                 assert_eq!(events.len(), 2);
5261                 events[1].clone()
5262         } else {
5263                 assert_eq!(events.len(), 1);
5264                 events[0].clone()
5265         };
5266         match close_event {
5267                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5268                 _ => panic!("Unexpected event"),
5269         }
5270
5271         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5272         check_closed_broadcast!(nodes[2], true);
5273         if deliver_last_raa {
5274                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5275         } else {
5276                 expect_pending_htlcs_forwardable!(nodes[2]);
5277         }
5278         check_added_monitors!(nodes[2], 3);
5279
5280         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5281         assert_eq!(cs_msgs.len(), 2);
5282         let mut a_done = false;
5283         for msg in cs_msgs {
5284                 match msg {
5285                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5286                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5287                                 // should be failed-backwards here.
5288                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5289                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5290                                         for htlc in &updates.update_fail_htlcs {
5291                                                 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 });
5292                                         }
5293                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5294                                         assert!(!a_done);
5295                                         a_done = true;
5296                                         &nodes[0]
5297                                 } else {
5298                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5299                                         for htlc in &updates.update_fail_htlcs {
5300                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5301                                         }
5302                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5303                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5304                                         &nodes[1]
5305                                 };
5306                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5307                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5308                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5309                                 if announce_latest {
5310                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5311                                         if *node_id == nodes[0].node.get_our_node_id() {
5312                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5313                                         }
5314                                 }
5315                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5316                         },
5317                         _ => panic!("Unexpected event"),
5318                 }
5319         }
5320
5321         let as_events = nodes[0].node.get_and_clear_pending_events();
5322         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5323         let mut as_failds = HashSet::new();
5324         let mut as_updates = 0;
5325         for event in as_events.iter() {
5326                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5327                         assert!(as_failds.insert(*payment_hash));
5328                         if *payment_hash != payment_hash_2 {
5329                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5330                         } else {
5331                                 assert!(!rejected_by_dest);
5332                         }
5333                         if network_update.is_some() {
5334                                 as_updates += 1;
5335                         }
5336                 } else { panic!("Unexpected event"); }
5337         }
5338         assert!(as_failds.contains(&payment_hash_1));
5339         assert!(as_failds.contains(&payment_hash_2));
5340         if announce_latest {
5341                 assert!(as_failds.contains(&payment_hash_3));
5342                 assert!(as_failds.contains(&payment_hash_5));
5343         }
5344         assert!(as_failds.contains(&payment_hash_6));
5345
5346         let bs_events = nodes[1].node.get_and_clear_pending_events();
5347         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5348         let mut bs_failds = HashSet::new();
5349         let mut bs_updates = 0;
5350         for event in bs_events.iter() {
5351                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5352                         assert!(bs_failds.insert(*payment_hash));
5353                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5354                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5355                         } else {
5356                                 assert!(!rejected_by_dest);
5357                         }
5358                         if network_update.is_some() {
5359                                 bs_updates += 1;
5360                         }
5361                 } else { panic!("Unexpected event"); }
5362         }
5363         assert!(bs_failds.contains(&payment_hash_1));
5364         assert!(bs_failds.contains(&payment_hash_2));
5365         if announce_latest {
5366                 assert!(bs_failds.contains(&payment_hash_4));
5367         }
5368         assert!(bs_failds.contains(&payment_hash_5));
5369
5370         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5371         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5372         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5373         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5374         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5375         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5376 }
5377
5378 #[test]
5379 fn test_fail_backwards_latest_remote_announce_a() {
5380         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5381 }
5382
5383 #[test]
5384 fn test_fail_backwards_latest_remote_announce_b() {
5385         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5386 }
5387
5388 #[test]
5389 fn test_fail_backwards_previous_remote_announce() {
5390         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5391         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5392         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5393 }
5394
5395 #[test]
5396 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5397         let chanmon_cfgs = create_chanmon_cfgs(2);
5398         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5399         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5400         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5401
5402         // Create some initial channels
5403         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5404
5405         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5406         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5407         assert_eq!(local_txn[0].input.len(), 1);
5408         check_spends!(local_txn[0], chan_1.3);
5409
5410         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5411         mine_transaction(&nodes[0], &local_txn[0]);
5412         check_closed_broadcast!(nodes[0], true);
5413         check_added_monitors!(nodes[0], 1);
5414         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5415         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5416
5417         let htlc_timeout = {
5418                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5419                 assert_eq!(node_txn.len(), 2);
5420                 check_spends!(node_txn[0], chan_1.3);
5421                 assert_eq!(node_txn[1].input.len(), 1);
5422                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5423                 check_spends!(node_txn[1], local_txn[0]);
5424                 node_txn[1].clone()
5425         };
5426
5427         mine_transaction(&nodes[0], &htlc_timeout);
5428         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5429         expect_payment_failed!(nodes[0], our_payment_hash, true);
5430
5431         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5432         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5433         assert_eq!(spend_txn.len(), 3);
5434         check_spends!(spend_txn[0], local_txn[0]);
5435         assert_eq!(spend_txn[1].input.len(), 1);
5436         check_spends!(spend_txn[1], htlc_timeout);
5437         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5438         assert_eq!(spend_txn[2].input.len(), 2);
5439         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5440         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5441                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5442 }
5443
5444 #[test]
5445 fn test_key_derivation_params() {
5446         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5447         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5448         // let us re-derive the channel key set to then derive a delayed_payment_key.
5449
5450         let chanmon_cfgs = create_chanmon_cfgs(3);
5451
5452         // We manually create the node configuration to backup the seed.
5453         let seed = [42; 32];
5454         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5455         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);
5456         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: &chanmon_cfgs[0].network_graph, node_seed: seed, features: InitFeatures::known() };
5457         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5458         node_cfgs.remove(0);
5459         node_cfgs.insert(0, node);
5460
5461         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5462         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5463
5464         // Create some initial channels
5465         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5466         // for node 0
5467         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5468         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5469         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5470
5471         // Ensure all nodes are at the same height
5472         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5473         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5474         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5475         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5476
5477         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5478         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5479         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5480         assert_eq!(local_txn_1[0].input.len(), 1);
5481         check_spends!(local_txn_1[0], chan_1.3);
5482
5483         // We check funding pubkey are unique
5484         let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][36..69]));
5485         let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][36..69]));
5486         if from_0_funding_key_0 == from_1_funding_key_0
5487             || from_0_funding_key_0 == from_1_funding_key_1
5488             || from_0_funding_key_1 == from_1_funding_key_0
5489             || from_0_funding_key_1 == from_1_funding_key_1 {
5490                 panic!("Funding pubkeys aren't unique");
5491         }
5492
5493         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5494         mine_transaction(&nodes[0], &local_txn_1[0]);
5495         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5496         check_closed_broadcast!(nodes[0], true);
5497         check_added_monitors!(nodes[0], 1);
5498         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5499
5500         let htlc_timeout = {
5501                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5502                 assert_eq!(node_txn[1].input.len(), 1);
5503                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5504                 check_spends!(node_txn[1], local_txn_1[0]);
5505                 node_txn[1].clone()
5506         };
5507
5508         mine_transaction(&nodes[0], &htlc_timeout);
5509         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5510         expect_payment_failed!(nodes[0], our_payment_hash, true);
5511
5512         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5513         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5514         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5515         assert_eq!(spend_txn.len(), 3);
5516         check_spends!(spend_txn[0], local_txn_1[0]);
5517         assert_eq!(spend_txn[1].input.len(), 1);
5518         check_spends!(spend_txn[1], htlc_timeout);
5519         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5520         assert_eq!(spend_txn[2].input.len(), 2);
5521         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5522         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5523                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5524 }
5525
5526 #[test]
5527 fn test_static_output_closing_tx() {
5528         let chanmon_cfgs = create_chanmon_cfgs(2);
5529         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5530         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5531         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5532
5533         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5534
5535         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5536         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5537
5538         mine_transaction(&nodes[0], &closing_tx);
5539         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5540         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5541
5542         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5543         assert_eq!(spend_txn.len(), 1);
5544         check_spends!(spend_txn[0], closing_tx);
5545
5546         mine_transaction(&nodes[1], &closing_tx);
5547         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5548         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5549
5550         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5551         assert_eq!(spend_txn.len(), 1);
5552         check_spends!(spend_txn[0], closing_tx);
5553 }
5554
5555 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5556         let chanmon_cfgs = create_chanmon_cfgs(2);
5557         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5558         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5559         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5560         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5561
5562         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5563
5564         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5565         // present in B's local commitment transaction, but none of A's commitment transactions.
5566         assert!(nodes[1].node.claim_funds(our_payment_preimage));
5567         check_added_monitors!(nodes[1], 1);
5568
5569         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5570         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5571         let events = nodes[0].node.get_and_clear_pending_events();
5572         assert_eq!(events.len(), 1);
5573         match events[0] {
5574                 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
5575                         assert_eq!(payment_preimage, our_payment_preimage);
5576                         assert_eq!(payment_hash, our_payment_hash);
5577                 },
5578                 _ => panic!("Unexpected event"),
5579         }
5580
5581         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5582         check_added_monitors!(nodes[0], 1);
5583         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5584         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5585         check_added_monitors!(nodes[1], 1);
5586
5587         let starting_block = nodes[1].best_block_info();
5588         let mut block = Block {
5589                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5590                 txdata: vec![],
5591         };
5592         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5593                 connect_block(&nodes[1], &block);
5594                 block.header.prev_blockhash = block.block_hash();
5595         }
5596         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5597         check_closed_broadcast!(nodes[1], true);
5598         check_added_monitors!(nodes[1], 1);
5599         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5600 }
5601
5602 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5603         let chanmon_cfgs = create_chanmon_cfgs(2);
5604         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5605         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5606         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5607         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5608
5609         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5610         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5611         check_added_monitors!(nodes[0], 1);
5612
5613         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5614
5615         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5616         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5617         // to "time out" the HTLC.
5618
5619         let starting_block = nodes[1].best_block_info();
5620         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5621
5622         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5623                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5624                 header.prev_blockhash = header.block_hash();
5625         }
5626         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5627         check_closed_broadcast!(nodes[0], true);
5628         check_added_monitors!(nodes[0], 1);
5629         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5630 }
5631
5632 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5633         let chanmon_cfgs = create_chanmon_cfgs(3);
5634         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5635         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5636         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5637         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5638
5639         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5640         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5641         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5642         // actually revoked.
5643         let htlc_value = if use_dust { 50000 } else { 3000000 };
5644         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5645         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5646         expect_pending_htlcs_forwardable!(nodes[1]);
5647         check_added_monitors!(nodes[1], 1);
5648
5649         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5650         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5651         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5652         check_added_monitors!(nodes[0], 1);
5653         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5654         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5655         check_added_monitors!(nodes[1], 1);
5656         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5657         check_added_monitors!(nodes[1], 1);
5658         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5659
5660         if check_revoke_no_close {
5661                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5662                 check_added_monitors!(nodes[0], 1);
5663         }
5664
5665         let starting_block = nodes[1].best_block_info();
5666         let mut block = Block {
5667                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5668                 txdata: vec![],
5669         };
5670         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5671                 connect_block(&nodes[0], &block);
5672                 block.header.prev_blockhash = block.block_hash();
5673         }
5674         if !check_revoke_no_close {
5675                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5676                 check_closed_broadcast!(nodes[0], true);
5677                 check_added_monitors!(nodes[0], 1);
5678                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5679         } else {
5680                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5681         }
5682 }
5683
5684 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5685 // There are only a few cases to test here:
5686 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5687 //    broadcastable commitment transactions result in channel closure,
5688 //  * its included in an unrevoked-but-previous remote commitment transaction,
5689 //  * its included in the latest remote or local commitment transactions.
5690 // We test each of the three possible commitment transactions individually and use both dust and
5691 // non-dust HTLCs.
5692 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5693 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5694 // tested for at least one of the cases in other tests.
5695 #[test]
5696 fn htlc_claim_single_commitment_only_a() {
5697         do_htlc_claim_local_commitment_only(true);
5698         do_htlc_claim_local_commitment_only(false);
5699
5700         do_htlc_claim_current_remote_commitment_only(true);
5701         do_htlc_claim_current_remote_commitment_only(false);
5702 }
5703
5704 #[test]
5705 fn htlc_claim_single_commitment_only_b() {
5706         do_htlc_claim_previous_remote_commitment_only(true, false);
5707         do_htlc_claim_previous_remote_commitment_only(false, false);
5708         do_htlc_claim_previous_remote_commitment_only(true, true);
5709         do_htlc_claim_previous_remote_commitment_only(false, true);
5710 }
5711
5712 #[test]
5713 #[should_panic]
5714 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5715         let chanmon_cfgs = create_chanmon_cfgs(2);
5716         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5717         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5718         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5719         //Force duplicate channel ids
5720         for node in nodes.iter() {
5721                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5722         }
5723
5724         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5725         let channel_value_satoshis=10000;
5726         let push_msat=10001;
5727         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5728         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5729         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5730
5731         //Create a second channel with a channel_id collision
5732         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5733 }
5734
5735 #[test]
5736 fn bolt2_open_channel_sending_node_checks_part2() {
5737         let chanmon_cfgs = create_chanmon_cfgs(2);
5738         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5739         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5740         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5741
5742         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5743         let channel_value_satoshis=2^24;
5744         let push_msat=10001;
5745         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5746
5747         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5748         let channel_value_satoshis=10000;
5749         // Test when push_msat is equal to 1000 * funding_satoshis.
5750         let push_msat=1000*channel_value_satoshis+1;
5751         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5752
5753         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5754         let channel_value_satoshis=10000;
5755         let push_msat=10001;
5756         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
5757         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5758         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5759
5760         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5761         // 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
5762         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5763
5764         // 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.
5765         assert!(BREAKDOWN_TIMEOUT>0);
5766         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5767
5768         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5769         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5770         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5771
5772         // 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.
5773         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5774         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5775         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5776         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5777         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5778 }
5779
5780 #[test]
5781 fn bolt2_open_channel_sane_dust_limit() {
5782         let chanmon_cfgs = create_chanmon_cfgs(2);
5783         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5784         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5785         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5786
5787         let channel_value_satoshis=1000000;
5788         let push_msat=10001;
5789         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5790         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5791         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5792         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5793
5794         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5795         let events = nodes[1].node.get_and_clear_pending_msg_events();
5796         let err_msg = match events[0] {
5797                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5798                         msg.clone()
5799                 },
5800                 _ => panic!("Unexpected event"),
5801         };
5802         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5803 }
5804
5805 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5806 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5807 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5808 // is no longer affordable once it's freed.
5809 #[test]
5810 fn test_fail_holding_cell_htlc_upon_free() {
5811         let chanmon_cfgs = create_chanmon_cfgs(2);
5812         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5813         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5814         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5815         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5816
5817         // First nodes[0] generates an update_fee, setting the channel's
5818         // pending_update_fee.
5819         {
5820                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5821                 *feerate_lock += 20;
5822         }
5823         nodes[0].node.timer_tick_occurred();
5824         check_added_monitors!(nodes[0], 1);
5825
5826         let events = nodes[0].node.get_and_clear_pending_msg_events();
5827         assert_eq!(events.len(), 1);
5828         let (update_msg, commitment_signed) = match events[0] {
5829                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5830                         (update_fee.as_ref(), commitment_signed)
5831                 },
5832                 _ => panic!("Unexpected event"),
5833         };
5834
5835         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5836
5837         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5838         let channel_reserve = chan_stat.channel_reserve_msat;
5839         let feerate = get_feerate!(nodes[0], chan.2);
5840
5841         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5842         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5843         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5844
5845         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5846         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
5847         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5848         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5849
5850         // Flush the pending fee update.
5851         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5852         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5853         check_added_monitors!(nodes[1], 1);
5854         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5855         check_added_monitors!(nodes[0], 1);
5856
5857         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5858         // HTLC, but now that the fee has been raised the payment will now fail, causing
5859         // us to surface its failure to the user.
5860         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5861         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5862         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);
5863         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 {}",
5864                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5865         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5866
5867         // Check that the payment failed to be sent out.
5868         let events = nodes[0].node.get_and_clear_pending_events();
5869         assert_eq!(events.len(), 1);
5870         match &events[0] {
5871                 &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, .. } => {
5872                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
5873                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5874                         assert_eq!(*rejected_by_dest, false);
5875                         assert_eq!(*all_paths_failed, true);
5876                         assert_eq!(*network_update, None);
5877                         assert_eq!(*short_channel_id, None);
5878                         assert_eq!(*error_code, None);
5879                         assert_eq!(*error_data, None);
5880                 },
5881                 _ => panic!("Unexpected event"),
5882         }
5883 }
5884
5885 // Test that if multiple HTLCs are released from the holding cell and one is
5886 // valid but the other is no longer valid upon release, the valid HTLC can be
5887 // successfully completed while the other one fails as expected.
5888 #[test]
5889 fn test_free_and_fail_holding_cell_htlcs() {
5890         let chanmon_cfgs = create_chanmon_cfgs(2);
5891         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5892         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5893         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5894         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5895
5896         // First nodes[0] generates an update_fee, setting the channel's
5897         // pending_update_fee.
5898         {
5899                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5900                 *feerate_lock += 200;
5901         }
5902         nodes[0].node.timer_tick_occurred();
5903         check_added_monitors!(nodes[0], 1);
5904
5905         let events = nodes[0].node.get_and_clear_pending_msg_events();
5906         assert_eq!(events.len(), 1);
5907         let (update_msg, commitment_signed) = match events[0] {
5908                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5909                         (update_fee.as_ref(), commitment_signed)
5910                 },
5911                 _ => panic!("Unexpected event"),
5912         };
5913
5914         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5915
5916         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5917         let channel_reserve = chan_stat.channel_reserve_msat;
5918         let feerate = get_feerate!(nodes[0], chan.2);
5919
5920         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5921         let amt_1 = 20000;
5922         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
5923         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5924         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5925
5926         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5927         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
5928         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5929         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5930         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
5931         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5932         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5933
5934         // Flush the pending fee update.
5935         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5936         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5937         check_added_monitors!(nodes[1], 1);
5938         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5939         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5940         check_added_monitors!(nodes[0], 2);
5941
5942         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5943         // but now that the fee has been raised the second payment will now fail, causing us
5944         // to surface its failure to the user. The first payment should succeed.
5945         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5946         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5947         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);
5948         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 {}",
5949                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5950         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5951
5952         // Check that the second payment failed to be sent out.
5953         let events = nodes[0].node.get_and_clear_pending_events();
5954         assert_eq!(events.len(), 1);
5955         match &events[0] {
5956                 &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, .. } => {
5957                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5958                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5959                         assert_eq!(*rejected_by_dest, false);
5960                         assert_eq!(*all_paths_failed, true);
5961                         assert_eq!(*network_update, None);
5962                         assert_eq!(*short_channel_id, None);
5963                         assert_eq!(*error_code, None);
5964                         assert_eq!(*error_data, None);
5965                 },
5966                 _ => panic!("Unexpected event"),
5967         }
5968
5969         // Complete the first payment and the RAA from the fee update.
5970         let (payment_event, send_raa_event) = {
5971                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5972                 assert_eq!(msgs.len(), 2);
5973                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5974         };
5975         let raa = match send_raa_event {
5976                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5977                 _ => panic!("Unexpected event"),
5978         };
5979         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5980         check_added_monitors!(nodes[1], 1);
5981         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5982         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5983         let events = nodes[1].node.get_and_clear_pending_events();
5984         assert_eq!(events.len(), 1);
5985         match events[0] {
5986                 Event::PendingHTLCsForwardable { .. } => {},
5987                 _ => panic!("Unexpected event"),
5988         }
5989         nodes[1].node.process_pending_htlc_forwards();
5990         let events = nodes[1].node.get_and_clear_pending_events();
5991         assert_eq!(events.len(), 1);
5992         match events[0] {
5993                 Event::PaymentReceived { .. } => {},
5994                 _ => panic!("Unexpected event"),
5995         }
5996         nodes[1].node.claim_funds(payment_preimage_1);
5997         check_added_monitors!(nodes[1], 1);
5998         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5999         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6000         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6001         let events = nodes[0].node.get_and_clear_pending_events();
6002         assert_eq!(events.len(), 1);
6003         match events[0] {
6004                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
6005                         assert_eq!(*payment_preimage, payment_preimage_1);
6006                         assert_eq!(*payment_hash, payment_hash_1);
6007                 }
6008                 _ => panic!("Unexpected event"),
6009         }
6010 }
6011
6012 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6013 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6014 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6015 // once it's freed.
6016 #[test]
6017 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6018         let chanmon_cfgs = create_chanmon_cfgs(3);
6019         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6020         // When this test was written, the default base fee floated based on the HTLC count.
6021         // It is now fixed, so we simply set the fee to the expected value here.
6022         let mut config = test_default_channel_config();
6023         config.channel_options.forwarding_fee_base_msat = 196;
6024         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6025         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6026         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6027         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6028
6029         // First nodes[1] generates an update_fee, setting the channel's
6030         // pending_update_fee.
6031         {
6032                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6033                 *feerate_lock += 20;
6034         }
6035         nodes[1].node.timer_tick_occurred();
6036         check_added_monitors!(nodes[1], 1);
6037
6038         let events = nodes[1].node.get_and_clear_pending_msg_events();
6039         assert_eq!(events.len(), 1);
6040         let (update_msg, commitment_signed) = match events[0] {
6041                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6042                         (update_fee.as_ref(), commitment_signed)
6043                 },
6044                 _ => panic!("Unexpected event"),
6045         };
6046
6047         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6048
6049         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6050         let channel_reserve = chan_stat.channel_reserve_msat;
6051         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6052
6053         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6054         let feemsat = 239;
6055         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6056         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6057         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6058         let payment_event = {
6059                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6060                 check_added_monitors!(nodes[0], 1);
6061
6062                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6063                 assert_eq!(events.len(), 1);
6064
6065                 SendEvent::from_event(events.remove(0))
6066         };
6067         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6068         check_added_monitors!(nodes[1], 0);
6069         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6070         expect_pending_htlcs_forwardable!(nodes[1]);
6071
6072         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6073         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6074
6075         // Flush the pending fee update.
6076         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6077         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6078         check_added_monitors!(nodes[2], 1);
6079         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6080         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6081         check_added_monitors!(nodes[1], 2);
6082
6083         // A final RAA message is generated to finalize the fee update.
6084         let events = nodes[1].node.get_and_clear_pending_msg_events();
6085         assert_eq!(events.len(), 1);
6086
6087         let raa_msg = match &events[0] {
6088                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6089                         msg.clone()
6090                 },
6091                 _ => panic!("Unexpected event"),
6092         };
6093
6094         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6095         check_added_monitors!(nodes[2], 1);
6096         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6097
6098         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6099         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6100         assert_eq!(process_htlc_forwards_event.len(), 1);
6101         match &process_htlc_forwards_event[0] {
6102                 &Event::PendingHTLCsForwardable { .. } => {},
6103                 _ => panic!("Unexpected event"),
6104         }
6105
6106         // In response, we call ChannelManager's process_pending_htlc_forwards
6107         nodes[1].node.process_pending_htlc_forwards();
6108         check_added_monitors!(nodes[1], 1);
6109
6110         // This causes the HTLC to be failed backwards.
6111         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6112         assert_eq!(fail_event.len(), 1);
6113         let (fail_msg, commitment_signed) = match &fail_event[0] {
6114                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6115                         assert_eq!(updates.update_add_htlcs.len(), 0);
6116                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6117                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6118                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6119                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6120                 },
6121                 _ => panic!("Unexpected event"),
6122         };
6123
6124         // Pass the failure messages back to nodes[0].
6125         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6126         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6127
6128         // Complete the HTLC failure+removal process.
6129         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6130         check_added_monitors!(nodes[0], 1);
6131         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6132         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6133         check_added_monitors!(nodes[1], 2);
6134         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6135         assert_eq!(final_raa_event.len(), 1);
6136         let raa = match &final_raa_event[0] {
6137                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6138                 _ => panic!("Unexpected event"),
6139         };
6140         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6141         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6142         check_added_monitors!(nodes[0], 1);
6143 }
6144
6145 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6146 // 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.
6147 //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.
6148
6149 #[test]
6150 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6151         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6152         let chanmon_cfgs = create_chanmon_cfgs(2);
6153         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6154         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6155         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6156         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6157
6158         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6159         route.paths[0][0].fee_msat = 100;
6160
6161         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6162                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6163         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6164         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6165 }
6166
6167 #[test]
6168 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6169         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6170         let chanmon_cfgs = create_chanmon_cfgs(2);
6171         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6172         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6173         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6174         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6175
6176         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6177         route.paths[0][0].fee_msat = 0;
6178         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6179                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6180
6181         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6182         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6183 }
6184
6185 #[test]
6186 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6187         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6188         let chanmon_cfgs = create_chanmon_cfgs(2);
6189         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6190         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6191         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6192         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6193
6194         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6195         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6196         check_added_monitors!(nodes[0], 1);
6197         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6198         updates.update_add_htlcs[0].amount_msat = 0;
6199
6200         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6201         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6202         check_closed_broadcast!(nodes[1], true).unwrap();
6203         check_added_monitors!(nodes[1], 1);
6204         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6205 }
6206
6207 #[test]
6208 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6209         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6210         //It is enforced when constructing a route.
6211         let chanmon_cfgs = create_chanmon_cfgs(2);
6212         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6213         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6214         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6215         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6216
6217         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], vec![], 100000000, 500000001);
6218         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6219                 assert_eq!(err, &"Channel CLTV overflowed?"));
6220 }
6221
6222 #[test]
6223 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6224         //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.
6225         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6226         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6227         let chanmon_cfgs = create_chanmon_cfgs(2);
6228         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6229         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6230         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6231         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6232         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6233
6234         for i in 0..max_accepted_htlcs {
6235                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6236                 let payment_event = {
6237                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6238                         check_added_monitors!(nodes[0], 1);
6239
6240                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6241                         assert_eq!(events.len(), 1);
6242                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6243                                 assert_eq!(htlcs[0].htlc_id, i);
6244                         } else {
6245                                 assert!(false);
6246                         }
6247                         SendEvent::from_event(events.remove(0))
6248                 };
6249                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6250                 check_added_monitors!(nodes[1], 0);
6251                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6252
6253                 expect_pending_htlcs_forwardable!(nodes[1]);
6254                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6255         }
6256         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6257         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6258                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6259
6260         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6261         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6262 }
6263
6264 #[test]
6265 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6266         //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.
6267         let chanmon_cfgs = create_chanmon_cfgs(2);
6268         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6269         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6270         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6271         let channel_value = 100000;
6272         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6273         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6274
6275         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6276
6277         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6278         // Manually create a route over our max in flight (which our router normally automatically
6279         // limits us to.
6280         route.paths[0][0].fee_msat =  max_in_flight + 1;
6281         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6282                 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)));
6283
6284         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6285         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);
6286
6287         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6288 }
6289
6290 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6291 #[test]
6292 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6293         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6294         let chanmon_cfgs = create_chanmon_cfgs(2);
6295         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6296         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6297         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6298         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6299         let htlc_minimum_msat: u64;
6300         {
6301                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6302                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6303                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6304         }
6305
6306         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6307         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6308         check_added_monitors!(nodes[0], 1);
6309         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6310         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6311         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6312         assert!(nodes[1].node.list_channels().is_empty());
6313         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6314         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()));
6315         check_added_monitors!(nodes[1], 1);
6316         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6317 }
6318
6319 #[test]
6320 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6321         //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
6322         let chanmon_cfgs = create_chanmon_cfgs(2);
6323         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6324         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6325         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6326         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6327
6328         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6329         let channel_reserve = chan_stat.channel_reserve_msat;
6330         let feerate = get_feerate!(nodes[0], chan.2);
6331         // The 2* and +1 are for the fee spike reserve.
6332         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6333
6334         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6335         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6336         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6337         check_added_monitors!(nodes[0], 1);
6338         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6339
6340         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6341         // at this time channel-initiatee receivers are not required to enforce that senders
6342         // respect the fee_spike_reserve.
6343         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6344         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6345
6346         assert!(nodes[1].node.list_channels().is_empty());
6347         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6348         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6349         check_added_monitors!(nodes[1], 1);
6350         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6351 }
6352
6353 #[test]
6354 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6355         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6356         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6357         let chanmon_cfgs = create_chanmon_cfgs(2);
6358         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6359         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6360         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6361         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6362
6363         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6364         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6365         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6366         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6367         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6368         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6369
6370         let mut msg = msgs::UpdateAddHTLC {
6371                 channel_id: chan.2,
6372                 htlc_id: 0,
6373                 amount_msat: 1000,
6374                 payment_hash: our_payment_hash,
6375                 cltv_expiry: htlc_cltv,
6376                 onion_routing_packet: onion_packet.clone(),
6377         };
6378
6379         for i in 0..super::channel::OUR_MAX_HTLCS {
6380                 msg.htlc_id = i as u64;
6381                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6382         }
6383         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6384         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6385
6386         assert!(nodes[1].node.list_channels().is_empty());
6387         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6388         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6389         check_added_monitors!(nodes[1], 1);
6390         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6391 }
6392
6393 #[test]
6394 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6395         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6396         let chanmon_cfgs = create_chanmon_cfgs(2);
6397         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6398         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6399         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6400         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6401
6402         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6403         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6404         check_added_monitors!(nodes[0], 1);
6405         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6406         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6407         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6408
6409         assert!(nodes[1].node.list_channels().is_empty());
6410         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6411         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6412         check_added_monitors!(nodes[1], 1);
6413         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6414 }
6415
6416 #[test]
6417 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6418         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6419         let chanmon_cfgs = create_chanmon_cfgs(2);
6420         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6421         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6422         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6423
6424         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6425         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6426         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6427         check_added_monitors!(nodes[0], 1);
6428         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6429         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6430         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6431
6432         assert!(nodes[1].node.list_channels().is_empty());
6433         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6434         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6435         check_added_monitors!(nodes[1], 1);
6436         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6437 }
6438
6439 #[test]
6440 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6441         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6442         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6443         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6444         let chanmon_cfgs = create_chanmon_cfgs(2);
6445         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6446         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6447         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6448
6449         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6450         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6451         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6452         check_added_monitors!(nodes[0], 1);
6453         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6454         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6455
6456         //Disconnect and Reconnect
6457         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6458         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6459         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6460         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6461         assert_eq!(reestablish_1.len(), 1);
6462         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6463         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6464         assert_eq!(reestablish_2.len(), 1);
6465         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6466         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6467         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6468         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6469
6470         //Resend HTLC
6471         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6472         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6473         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6474         check_added_monitors!(nodes[1], 1);
6475         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6476
6477         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6478
6479         assert!(nodes[1].node.list_channels().is_empty());
6480         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6481         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6482         check_added_monitors!(nodes[1], 1);
6483         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6484 }
6485
6486 #[test]
6487 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6488         //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.
6489
6490         let chanmon_cfgs = create_chanmon_cfgs(2);
6491         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6492         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6493         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6494         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6495         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6496         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6497
6498         check_added_monitors!(nodes[0], 1);
6499         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6500         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6501
6502         let update_msg = msgs::UpdateFulfillHTLC{
6503                 channel_id: chan.2,
6504                 htlc_id: 0,
6505                 payment_preimage: our_payment_preimage,
6506         };
6507
6508         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6509
6510         assert!(nodes[0].node.list_channels().is_empty());
6511         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6512         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()));
6513         check_added_monitors!(nodes[0], 1);
6514         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6515 }
6516
6517 #[test]
6518 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6519         //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.
6520
6521         let chanmon_cfgs = create_chanmon_cfgs(2);
6522         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6523         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6524         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6525         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6526
6527         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6528         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6529         check_added_monitors!(nodes[0], 1);
6530         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6531         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6532
6533         let update_msg = msgs::UpdateFailHTLC{
6534                 channel_id: chan.2,
6535                 htlc_id: 0,
6536                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6537         };
6538
6539         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6540
6541         assert!(nodes[0].node.list_channels().is_empty());
6542         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6543         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()));
6544         check_added_monitors!(nodes[0], 1);
6545         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6546 }
6547
6548 #[test]
6549 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6550         //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.
6551
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(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6557
6558         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6559         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6560         check_added_monitors!(nodes[0], 1);
6561         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6562         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6563         let update_msg = msgs::UpdateFailMalformedHTLC{
6564                 channel_id: chan.2,
6565                 htlc_id: 0,
6566                 sha256_of_onion: [1; 32],
6567                 failure_code: 0x8000,
6568         };
6569
6570         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6571
6572         assert!(nodes[0].node.list_channels().is_empty());
6573         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6574         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()));
6575         check_added_monitors!(nodes[0], 1);
6576         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6577 }
6578
6579 #[test]
6580 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6581         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6582
6583         let chanmon_cfgs = create_chanmon_cfgs(2);
6584         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6585         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6586         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6587         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6588
6589         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6590
6591         nodes[1].node.claim_funds(our_payment_preimage);
6592         check_added_monitors!(nodes[1], 1);
6593
6594         let events = nodes[1].node.get_and_clear_pending_msg_events();
6595         assert_eq!(events.len(), 1);
6596         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6597                 match events[0] {
6598                         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, .. } } => {
6599                                 assert!(update_add_htlcs.is_empty());
6600                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6601                                 assert!(update_fail_htlcs.is_empty());
6602                                 assert!(update_fail_malformed_htlcs.is_empty());
6603                                 assert!(update_fee.is_none());
6604                                 update_fulfill_htlcs[0].clone()
6605                         },
6606                         _ => panic!("Unexpected event"),
6607                 }
6608         };
6609
6610         update_fulfill_msg.htlc_id = 1;
6611
6612         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6613
6614         assert!(nodes[0].node.list_channels().is_empty());
6615         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6616         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6617         check_added_monitors!(nodes[0], 1);
6618         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6619 }
6620
6621 #[test]
6622 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6623         //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.
6624
6625         let chanmon_cfgs = create_chanmon_cfgs(2);
6626         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6627         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6628         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6629         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6630
6631         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6632
6633         nodes[1].node.claim_funds(our_payment_preimage);
6634         check_added_monitors!(nodes[1], 1);
6635
6636         let events = nodes[1].node.get_and_clear_pending_msg_events();
6637         assert_eq!(events.len(), 1);
6638         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6639                 match events[0] {
6640                         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, .. } } => {
6641                                 assert!(update_add_htlcs.is_empty());
6642                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6643                                 assert!(update_fail_htlcs.is_empty());
6644                                 assert!(update_fail_malformed_htlcs.is_empty());
6645                                 assert!(update_fee.is_none());
6646                                 update_fulfill_htlcs[0].clone()
6647                         },
6648                         _ => panic!("Unexpected event"),
6649                 }
6650         };
6651
6652         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6653
6654         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6655
6656         assert!(nodes[0].node.list_channels().is_empty());
6657         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6658         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6659         check_added_monitors!(nodes[0], 1);
6660         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6661 }
6662
6663 #[test]
6664 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6665         //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.
6666
6667         let chanmon_cfgs = create_chanmon_cfgs(2);
6668         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6669         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6670         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6671         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6672
6673         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6674         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6675         check_added_monitors!(nodes[0], 1);
6676
6677         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6678         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6679
6680         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6681         check_added_monitors!(nodes[1], 0);
6682         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6683
6684         let events = nodes[1].node.get_and_clear_pending_msg_events();
6685
6686         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6687                 match events[0] {
6688                         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, .. } } => {
6689                                 assert!(update_add_htlcs.is_empty());
6690                                 assert!(update_fulfill_htlcs.is_empty());
6691                                 assert!(update_fail_htlcs.is_empty());
6692                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6693                                 assert!(update_fee.is_none());
6694                                 update_fail_malformed_htlcs[0].clone()
6695                         },
6696                         _ => panic!("Unexpected event"),
6697                 }
6698         };
6699         update_msg.failure_code &= !0x8000;
6700         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6701
6702         assert!(nodes[0].node.list_channels().is_empty());
6703         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6704         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6705         check_added_monitors!(nodes[0], 1);
6706         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6707 }
6708
6709 #[test]
6710 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6711         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6712         //    * 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.
6713
6714         let chanmon_cfgs = create_chanmon_cfgs(3);
6715         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6716         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6717         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6718         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6719         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6720
6721         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6722
6723         //First hop
6724         let mut payment_event = {
6725                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6726                 check_added_monitors!(nodes[0], 1);
6727                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6728                 assert_eq!(events.len(), 1);
6729                 SendEvent::from_event(events.remove(0))
6730         };
6731         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6732         check_added_monitors!(nodes[1], 0);
6733         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6734         expect_pending_htlcs_forwardable!(nodes[1]);
6735         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6736         assert_eq!(events_2.len(), 1);
6737         check_added_monitors!(nodes[1], 1);
6738         payment_event = SendEvent::from_event(events_2.remove(0));
6739         assert_eq!(payment_event.msgs.len(), 1);
6740
6741         //Second Hop
6742         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6743         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6744         check_added_monitors!(nodes[2], 0);
6745         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6746
6747         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6748         assert_eq!(events_3.len(), 1);
6749         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6750                 match events_3[0] {
6751                         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 } } => {
6752                                 assert!(update_add_htlcs.is_empty());
6753                                 assert!(update_fulfill_htlcs.is_empty());
6754                                 assert!(update_fail_htlcs.is_empty());
6755                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6756                                 assert!(update_fee.is_none());
6757                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6758                         },
6759                         _ => panic!("Unexpected event"),
6760                 }
6761         };
6762
6763         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6764
6765         check_added_monitors!(nodes[1], 0);
6766         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6767         expect_pending_htlcs_forwardable!(nodes[1]);
6768         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6769         assert_eq!(events_4.len(), 1);
6770
6771         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6772         match events_4[0] {
6773                 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, .. } } => {
6774                         assert!(update_add_htlcs.is_empty());
6775                         assert!(update_fulfill_htlcs.is_empty());
6776                         assert_eq!(update_fail_htlcs.len(), 1);
6777                         assert!(update_fail_malformed_htlcs.is_empty());
6778                         assert!(update_fee.is_none());
6779                 },
6780                 _ => panic!("Unexpected event"),
6781         };
6782
6783         check_added_monitors!(nodes[1], 1);
6784 }
6785
6786 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6787         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6788         // 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
6789         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6790
6791         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6792         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6793         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6794         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6795         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6796         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6797
6798         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6799
6800         // We route 2 dust-HTLCs between A and B
6801         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6802         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6803         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6804
6805         // Cache one local commitment tx as previous
6806         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6807
6808         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6809         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
6810         check_added_monitors!(nodes[1], 0);
6811         expect_pending_htlcs_forwardable!(nodes[1]);
6812         check_added_monitors!(nodes[1], 1);
6813
6814         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6815         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6816         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6817         check_added_monitors!(nodes[0], 1);
6818
6819         // Cache one local commitment tx as lastest
6820         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6821
6822         let events = nodes[0].node.get_and_clear_pending_msg_events();
6823         match events[0] {
6824                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6825                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6826                 },
6827                 _ => panic!("Unexpected event"),
6828         }
6829         match events[1] {
6830                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6831                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6832                 },
6833                 _ => panic!("Unexpected event"),
6834         }
6835
6836         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6837         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6838         if announce_latest {
6839                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6840         } else {
6841                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6842         }
6843
6844         check_closed_broadcast!(nodes[0], true);
6845         check_added_monitors!(nodes[0], 1);
6846         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6847
6848         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6849         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6850         let events = nodes[0].node.get_and_clear_pending_events();
6851         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6852         assert_eq!(events.len(), 2);
6853         let mut first_failed = false;
6854         for event in events {
6855                 match event {
6856                         Event::PaymentPathFailed { payment_hash, .. } => {
6857                                 if payment_hash == payment_hash_1 {
6858                                         assert!(!first_failed);
6859                                         first_failed = true;
6860                                 } else {
6861                                         assert_eq!(payment_hash, payment_hash_2);
6862                                 }
6863                         }
6864                         _ => panic!("Unexpected event"),
6865                 }
6866         }
6867 }
6868
6869 #[test]
6870 fn test_failure_delay_dust_htlc_local_commitment() {
6871         do_test_failure_delay_dust_htlc_local_commitment(true);
6872         do_test_failure_delay_dust_htlc_local_commitment(false);
6873 }
6874
6875 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6876         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6877         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6878         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6879         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6880         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6881         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6882
6883         let chanmon_cfgs = create_chanmon_cfgs(3);
6884         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6885         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6886         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6887         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6888
6889         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6890
6891         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6892         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6893
6894         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6895         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6896
6897         // We revoked bs_commitment_tx
6898         if revoked {
6899                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6900                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6901         }
6902
6903         let mut timeout_tx = Vec::new();
6904         if local {
6905                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6906                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6907                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6908                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6909                 expect_payment_failed!(nodes[0], dust_hash, true);
6910
6911                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6912                 check_closed_broadcast!(nodes[0], true);
6913                 check_added_monitors!(nodes[0], 1);
6914                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6915                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
6916                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6917                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6918                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6919                 mine_transaction(&nodes[0], &timeout_tx[0]);
6920                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6921                 expect_payment_failed!(nodes[0], non_dust_hash, true);
6922         } else {
6923                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6924                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6925                 check_closed_broadcast!(nodes[0], true);
6926                 check_added_monitors!(nodes[0], 1);
6927                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6928                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6929                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6930                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
6931                 if !revoked {
6932                         expect_payment_failed!(nodes[0], dust_hash, true);
6933                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6934                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
6935                         mine_transaction(&nodes[0], &timeout_tx[0]);
6936                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6937                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6938                         expect_payment_failed!(nodes[0], non_dust_hash, true);
6939                 } else {
6940                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
6941                         // commitment tx
6942                         let events = nodes[0].node.get_and_clear_pending_events();
6943                         assert_eq!(events.len(), 2);
6944                         let first;
6945                         match events[0] {
6946                                 Event::PaymentPathFailed { payment_hash, .. } => {
6947                                         if payment_hash == dust_hash { first = true; }
6948                                         else { first = false; }
6949                                 },
6950                                 _ => panic!("Unexpected event"),
6951                         }
6952                         match events[1] {
6953                                 Event::PaymentPathFailed { payment_hash, .. } => {
6954                                         if first { assert_eq!(payment_hash, non_dust_hash); }
6955                                         else { assert_eq!(payment_hash, dust_hash); }
6956                                 },
6957                                 _ => panic!("Unexpected event"),
6958                         }
6959                 }
6960         }
6961 }
6962
6963 #[test]
6964 fn test_sweep_outbound_htlc_failure_update() {
6965         do_test_sweep_outbound_htlc_failure_update(false, true);
6966         do_test_sweep_outbound_htlc_failure_update(false, false);
6967         do_test_sweep_outbound_htlc_failure_update(true, false);
6968 }
6969
6970 #[test]
6971 fn test_user_configurable_csv_delay() {
6972         // We test our channel constructors yield errors when we pass them absurd csv delay
6973
6974         let mut low_our_to_self_config = UserConfig::default();
6975         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
6976         let mut high_their_to_self_config = UserConfig::default();
6977         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
6978         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6979         let chanmon_cfgs = create_chanmon_cfgs(2);
6980         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6981         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6982         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6983
6984         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6985         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0, &low_our_to_self_config) {
6986                 match error {
6987                         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())); },
6988                         _ => panic!("Unexpected event"),
6989                 }
6990         } else { assert!(false) }
6991
6992         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6993         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6994         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6995         open_channel.to_self_delay = 200;
6996         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0, &low_our_to_self_config) {
6997                 match error {
6998                         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()));  },
6999                         _ => panic!("Unexpected event"),
7000                 }
7001         } else { assert!(false); }
7002
7003         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7004         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7005         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()));
7006         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7007         accept_channel.to_self_delay = 200;
7008         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7009         let reason_msg;
7010         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7011                 match action {
7012                         &ErrorAction::SendErrorMessage { ref msg } => {
7013                                 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()));
7014                                 reason_msg = msg.data.clone();
7015                         },
7016                         _ => { panic!(); }
7017                 }
7018         } else { panic!(); }
7019         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7020
7021         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7022         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7023         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7024         open_channel.to_self_delay = 200;
7025         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0, &high_their_to_self_config) {
7026                 match error {
7027                         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())); },
7028                         _ => panic!("Unexpected event"),
7029                 }
7030         } else { assert!(false); }
7031 }
7032
7033 #[test]
7034 fn test_data_loss_protect() {
7035         // We want to be sure that :
7036         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7037         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7038         // * we close channel in case of detecting other being fallen behind
7039         // * we are able to claim our own outputs thanks to to_remote being static
7040         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7041         let persister;
7042         let logger;
7043         let fee_estimator;
7044         let tx_broadcaster;
7045         let chain_source;
7046         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7047         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7048         // during signing due to revoked tx
7049         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7050         let keys_manager = &chanmon_cfgs[0].keys_manager;
7051         let monitor;
7052         let node_state_0;
7053         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7054         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7055         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7056
7057         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7058
7059         // Cache node A state before any channel update
7060         let previous_node_state = nodes[0].node.encode();
7061         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7062         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7063
7064         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7065         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7066
7067         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7068         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7069
7070         // Restore node A from previous state
7071         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7072         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7073         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7074         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7075         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7076         persister = test_utils::TestPersister::new();
7077         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7078         node_state_0 = {
7079                 let mut channel_monitors = HashMap::new();
7080                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7081                 <(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 {
7082                         keys_manager: keys_manager,
7083                         fee_estimator: &fee_estimator,
7084                         chain_monitor: &monitor,
7085                         logger: &logger,
7086                         tx_broadcaster: &tx_broadcaster,
7087                         default_config: UserConfig::default(),
7088                         channel_monitors,
7089                 }).unwrap().1
7090         };
7091         nodes[0].node = &node_state_0;
7092         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7093         nodes[0].chain_monitor = &monitor;
7094         nodes[0].chain_source = &chain_source;
7095
7096         check_added_monitors!(nodes[0], 1);
7097
7098         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7099         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7100
7101         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7102
7103         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7104         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7105         check_added_monitors!(nodes[0], 1);
7106
7107         {
7108                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7109                 assert_eq!(node_txn.len(), 0);
7110         }
7111
7112         let mut reestablish_1 = Vec::with_capacity(1);
7113         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7114                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7115                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7116                         reestablish_1.push(msg.clone());
7117                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7118                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7119                         match action {
7120                                 &ErrorAction::SendErrorMessage { ref msg } => {
7121                                         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");
7122                                 },
7123                                 _ => panic!("Unexpected event!"),
7124                         }
7125                 } else {
7126                         panic!("Unexpected event")
7127                 }
7128         }
7129
7130         // Check we close channel detecting A is fallen-behind
7131         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7132         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7133         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7134         check_added_monitors!(nodes[1], 1);
7135
7136         // Check A is able to claim to_remote output
7137         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7138         assert_eq!(node_txn.len(), 1);
7139         check_spends!(node_txn[0], chan.3);
7140         assert_eq!(node_txn[0].output.len(), 2);
7141         mine_transaction(&nodes[0], &node_txn[0]);
7142         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7143         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { 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".to_string() });
7144         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7145         assert_eq!(spend_txn.len(), 1);
7146         check_spends!(spend_txn[0], node_txn[0]);
7147 }
7148
7149 #[test]
7150 fn test_check_htlc_underpaying() {
7151         // Send payment through A -> B but A is maliciously
7152         // sending a probe payment (i.e less than expected value0
7153         // to B, B should refuse payment.
7154
7155         let chanmon_cfgs = create_chanmon_cfgs(2);
7156         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7157         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7158         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7159
7160         // Create some initial channels
7161         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7162
7163         let scorer = test_utils::TestScorer::with_fixed_penalty(0);
7164         let payee = Payee::new(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7165         let route = get_route(&nodes[0].node.get_our_node_id(), &payee, nodes[0].network_graph, None, 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer).unwrap();
7166         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7167         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, 0).unwrap();
7168         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7169         check_added_monitors!(nodes[0], 1);
7170
7171         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7172         assert_eq!(events.len(), 1);
7173         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7174         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7175         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7176
7177         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7178         // and then will wait a second random delay before failing the HTLC back:
7179         expect_pending_htlcs_forwardable!(nodes[1]);
7180         expect_pending_htlcs_forwardable!(nodes[1]);
7181
7182         // Node 3 is expecting payment of 100_000 but received 10_000,
7183         // it should fail htlc like we didn't know the preimage.
7184         nodes[1].node.process_pending_htlc_forwards();
7185
7186         let events = nodes[1].node.get_and_clear_pending_msg_events();
7187         assert_eq!(events.len(), 1);
7188         let (update_fail_htlc, commitment_signed) = match events[0] {
7189                 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
7190                         assert!(update_add_htlcs.is_empty());
7191                         assert!(update_fulfill_htlcs.is_empty());
7192                         assert_eq!(update_fail_htlcs.len(), 1);
7193                         assert!(update_fail_malformed_htlcs.is_empty());
7194                         assert!(update_fee.is_none());
7195                         (update_fail_htlcs[0].clone(), commitment_signed)
7196                 },
7197                 _ => panic!("Unexpected event"),
7198         };
7199         check_added_monitors!(nodes[1], 1);
7200
7201         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7202         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7203
7204         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7205         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7206         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7207         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7208 }
7209
7210 #[test]
7211 fn test_announce_disable_channels() {
7212         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7213         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7214
7215         let chanmon_cfgs = create_chanmon_cfgs(2);
7216         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7217         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7218         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7219
7220         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7221         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7222         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7223
7224         // Disconnect peers
7225         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7226         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7227
7228         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7229         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7230         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7231         assert_eq!(msg_events.len(), 3);
7232         let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7233         for e in msg_events {
7234                 match e {
7235                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7236                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7237                                 // Check that each channel gets updated exactly once
7238                                 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7239                                         panic!("Generated ChannelUpdate for wrong chan!");
7240                                 }
7241                         },
7242                         _ => panic!("Unexpected event"),
7243                 }
7244         }
7245         // Reconnect peers
7246         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7247         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7248         assert_eq!(reestablish_1.len(), 3);
7249         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7250         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7251         assert_eq!(reestablish_2.len(), 3);
7252
7253         // Reestablish chan_1
7254         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7255         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7256         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7257         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7258         // Reestablish chan_2
7259         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7260         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7261         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7262         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7263         // Reestablish chan_3
7264         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7265         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7266         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7267         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7268
7269         nodes[0].node.timer_tick_occurred();
7270         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7271         nodes[0].node.timer_tick_occurred();
7272         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7273         assert_eq!(msg_events.len(), 3);
7274         chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7275         for e in msg_events {
7276                 match e {
7277                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7278                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7279                                 // Check that each channel gets updated exactly once
7280                                 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7281                                         panic!("Generated ChannelUpdate for wrong chan!");
7282                                 }
7283                         },
7284                         _ => panic!("Unexpected event"),
7285                 }
7286         }
7287 }
7288
7289 #[test]
7290 fn test_priv_forwarding_rejection() {
7291         // If we have a private channel with outbound liquidity, and
7292         // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7293         // to forward through that channel.
7294         let chanmon_cfgs = create_chanmon_cfgs(3);
7295         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7296         let mut no_announce_cfg = test_default_channel_config();
7297         no_announce_cfg.channel_options.announced_channel = false;
7298         no_announce_cfg.accept_forwards_to_priv_channels = false;
7299         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7300         let persister: test_utils::TestPersister;
7301         let new_chain_monitor: test_utils::TestChainMonitor;
7302         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7303         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7304
7305         let chan_id_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known()).2;
7306
7307         // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7308         // not send for private channels.
7309         nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7310         let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7311         nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7312         let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7313         nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7314
7315         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7316         nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7317         nodes[2].node.handle_funding_created(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingCreated, nodes[2].node.get_our_node_id()));
7318         check_added_monitors!(nodes[2], 1);
7319
7320         let cs_funding_signed = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[1].node.get_our_node_id());
7321         nodes[1].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &cs_funding_signed);
7322         check_added_monitors!(nodes[1], 1);
7323
7324         let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7325         confirm_transaction_at(&nodes[1], &tx, conf_height);
7326         connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7327         confirm_transaction_at(&nodes[2], &tx, conf_height);
7328         connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7329         let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7330         nodes[1].node.handle_funding_locked(&nodes[2].node.get_our_node_id(), &get_event_msg!(nodes[2], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id()));
7331         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7332         nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7333         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7334
7335         assert!(nodes[0].node.list_usable_channels()[0].is_public);
7336         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7337         assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7338
7339         // We should always be able to forward through nodes[1] as long as its out through a public
7340         // channel:
7341         send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7342
7343         // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7344         // to nodes[2], which should be rejected:
7345         let route_hint = RouteHint(vec![RouteHintHop {
7346                 src_node_id: nodes[1].node.get_our_node_id(),
7347                 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7348                 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7349                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7350                 htlc_minimum_msat: None,
7351                 htlc_maximum_msat: None,
7352         }]);
7353         let last_hops = vec![route_hint];
7354         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], last_hops, 10_000, TEST_FINAL_CLTV);
7355
7356         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7357         check_added_monitors!(nodes[0], 1);
7358         let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7359         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7360         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7361
7362         let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7363         assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7364         assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7365         assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7366         assert!(htlc_fail_updates.update_fee.is_none());
7367
7368         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7369         commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7370         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7371
7372         // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7373         // to true. Sadly there is currently no way to change it at runtime.
7374
7375         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7376         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7377
7378         let nodes_1_serialized = nodes[1].node.encode();
7379         let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7380         let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7381         get_monitor!(nodes[1], chan_id_1).write(&mut monitor_a_serialized).unwrap();
7382         get_monitor!(nodes[1], cs_funding_signed.channel_id).write(&mut monitor_b_serialized).unwrap();
7383
7384         persister = test_utils::TestPersister::new();
7385         let keys_manager = &chanmon_cfgs[1].keys_manager;
7386         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);
7387         nodes[1].chain_monitor = &new_chain_monitor;
7388
7389         let mut monitor_a_read = &monitor_a_serialized.0[..];
7390         let mut monitor_b_read = &monitor_b_serialized.0[..];
7391         let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7392         let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7393         assert!(monitor_a_read.is_empty());
7394         assert!(monitor_b_read.is_empty());
7395
7396         no_announce_cfg.accept_forwards_to_priv_channels = true;
7397
7398         let mut nodes_1_read = &nodes_1_serialized[..];
7399         let (_, nodes_1_deserialized_tmp) = {
7400                 let mut channel_monitors = HashMap::new();
7401                 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7402                 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7403                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7404                         default_config: no_announce_cfg,
7405                         keys_manager,
7406                         fee_estimator: node_cfgs[1].fee_estimator,
7407                         chain_monitor: nodes[1].chain_monitor,
7408                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7409                         logger: nodes[1].logger,
7410                         channel_monitors,
7411                 }).unwrap()
7412         };
7413         assert!(nodes_1_read.is_empty());
7414         nodes_1_deserialized = nodes_1_deserialized_tmp;
7415
7416         assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7417         assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7418         check_added_monitors!(nodes[1], 2);
7419         nodes[1].node = &nodes_1_deserialized;
7420
7421         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7422         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7423         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7424         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7425         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7426         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7427         get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7428         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7429
7430         nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7431         nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7432         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7433         let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7434         nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7435         nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7436         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7437         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7438
7439         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7440         check_added_monitors!(nodes[0], 1);
7441         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7442         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7443 }
7444
7445 #[test]
7446 fn test_bump_penalty_txn_on_revoked_commitment() {
7447         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7448         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7449
7450         let chanmon_cfgs = create_chanmon_cfgs(2);
7451         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7452         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7453         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7454
7455         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7456
7457         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7458         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], vec![], 3000000, 30);
7459         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7460
7461         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7462         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7463         assert_eq!(revoked_txn[0].output.len(), 4);
7464         assert_eq!(revoked_txn[0].input.len(), 1);
7465         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7466         let revoked_txid = revoked_txn[0].txid();
7467
7468         let mut penalty_sum = 0;
7469         for outp in revoked_txn[0].output.iter() {
7470                 if outp.script_pubkey.is_v0_p2wsh() {
7471                         penalty_sum += outp.value;
7472                 }
7473         }
7474
7475         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7476         let header_114 = connect_blocks(&nodes[1], 14);
7477
7478         // Actually revoke tx by claiming a HTLC
7479         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7480         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7481         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7482         check_added_monitors!(nodes[1], 1);
7483
7484         // One or more justice tx should have been broadcast, check it
7485         let penalty_1;
7486         let feerate_1;
7487         {
7488                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7489                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7490                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7491                 assert_eq!(node_txn[0].output.len(), 1);
7492                 check_spends!(node_txn[0], revoked_txn[0]);
7493                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7494                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7495                 penalty_1 = node_txn[0].txid();
7496                 node_txn.clear();
7497         };
7498
7499         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7500         connect_blocks(&nodes[1], 15);
7501         let mut penalty_2 = penalty_1;
7502         let mut feerate_2 = 0;
7503         {
7504                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7505                 assert_eq!(node_txn.len(), 1);
7506                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7507                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7508                         assert_eq!(node_txn[0].output.len(), 1);
7509                         check_spends!(node_txn[0], revoked_txn[0]);
7510                         penalty_2 = node_txn[0].txid();
7511                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7512                         assert_ne!(penalty_2, penalty_1);
7513                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7514                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7515                         // Verify 25% bump heuristic
7516                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7517                         node_txn.clear();
7518                 }
7519         }
7520         assert_ne!(feerate_2, 0);
7521
7522         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7523         connect_blocks(&nodes[1], 1);
7524         let penalty_3;
7525         let mut feerate_3 = 0;
7526         {
7527                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7528                 assert_eq!(node_txn.len(), 1);
7529                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7530                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7531                         assert_eq!(node_txn[0].output.len(), 1);
7532                         check_spends!(node_txn[0], revoked_txn[0]);
7533                         penalty_3 = node_txn[0].txid();
7534                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7535                         assert_ne!(penalty_3, penalty_2);
7536                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7537                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7538                         // Verify 25% bump heuristic
7539                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7540                         node_txn.clear();
7541                 }
7542         }
7543         assert_ne!(feerate_3, 0);
7544
7545         nodes[1].node.get_and_clear_pending_events();
7546         nodes[1].node.get_and_clear_pending_msg_events();
7547 }
7548
7549 #[test]
7550 fn test_bump_penalty_txn_on_revoked_htlcs() {
7551         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7552         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7553
7554         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7555         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7556         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7557         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7558         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7559
7560         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7561         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7562         let payee = Payee::new(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7563         let scorer = test_utils::TestScorer::with_fixed_penalty(0);
7564         let route = get_route(&nodes[0].node.get_our_node_id(), &payee, &nodes[0].network_graph, None,
7565                 3_000_000, 50, nodes[0].logger, &scorer).unwrap();
7566         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7567         let payee = Payee::new(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7568         let route = get_route(&nodes[1].node.get_our_node_id(), &payee, nodes[1].network_graph, None,
7569                 3_000_000, 50, nodes[0].logger, &scorer).unwrap();
7570         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7571
7572         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7573         assert_eq!(revoked_local_txn[0].input.len(), 1);
7574         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7575
7576         // Revoke local commitment tx
7577         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7578
7579         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7580         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7581         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7582         check_closed_broadcast!(nodes[1], true);
7583         check_added_monitors!(nodes[1], 1);
7584         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7585         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7586
7587         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7588         assert_eq!(revoked_htlc_txn.len(), 3);
7589         check_spends!(revoked_htlc_txn[1], chan.3);
7590
7591         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7592         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7593         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7594
7595         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7596         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7597         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7598         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7599
7600         // Broadcast set of revoked txn on A
7601         let hash_128 = connect_blocks(&nodes[0], 40);
7602         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7603         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7604         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7605         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7606         let events = nodes[0].node.get_and_clear_pending_events();
7607         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7608         match events[1] {
7609                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7610                 _ => panic!("Unexpected event"),
7611         }
7612         let first;
7613         let feerate_1;
7614         let penalty_txn;
7615         {
7616                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7617                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7618                 // Verify claim tx are spending revoked HTLC txn
7619
7620                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7621                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7622                 // which are included in the same block (they are broadcasted because we scan the
7623                 // transactions linearly and generate claims as we go, they likely should be removed in the
7624                 // future).
7625                 assert_eq!(node_txn[0].input.len(), 1);
7626                 check_spends!(node_txn[0], revoked_local_txn[0]);
7627                 assert_eq!(node_txn[1].input.len(), 1);
7628                 check_spends!(node_txn[1], revoked_local_txn[0]);
7629                 assert_eq!(node_txn[2].input.len(), 1);
7630                 check_spends!(node_txn[2], revoked_local_txn[0]);
7631
7632                 // Each of the three justice transactions claim a separate (single) output of the three
7633                 // available, which we check here:
7634                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7635                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7636                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7637
7638                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7639                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7640
7641                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7642                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7643                 // a remote commitment tx has already been confirmed).
7644                 check_spends!(node_txn[3], chan.3);
7645
7646                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7647                 // output, checked above).
7648                 assert_eq!(node_txn[4].input.len(), 2);
7649                 assert_eq!(node_txn[4].output.len(), 1);
7650                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7651
7652                 first = node_txn[4].txid();
7653                 // Store both feerates for later comparison
7654                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7655                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7656                 penalty_txn = vec![node_txn[2].clone()];
7657                 node_txn.clear();
7658         }
7659
7660         // Connect one more block to see if bumped penalty are issued for HTLC txn
7661         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7662         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7663         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7664         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7665         {
7666                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7667                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7668
7669                 check_spends!(node_txn[0], revoked_local_txn[0]);
7670                 check_spends!(node_txn[1], revoked_local_txn[0]);
7671                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7672                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7673                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7674                 } else {
7675                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7676                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7677                 }
7678
7679                 node_txn.clear();
7680         };
7681
7682         // Few more blocks to confirm penalty txn
7683         connect_blocks(&nodes[0], 4);
7684         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7685         let header_144 = connect_blocks(&nodes[0], 9);
7686         let node_txn = {
7687                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7688                 assert_eq!(node_txn.len(), 1);
7689
7690                 assert_eq!(node_txn[0].input.len(), 2);
7691                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7692                 // Verify bumped tx is different and 25% bump heuristic
7693                 assert_ne!(first, node_txn[0].txid());
7694                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7695                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7696                 assert!(feerate_2 * 100 > feerate_1 * 125);
7697                 let txn = vec![node_txn[0].clone()];
7698                 node_txn.clear();
7699                 txn
7700         };
7701         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7702         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7703         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7704         connect_blocks(&nodes[0], 20);
7705         {
7706                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7707                 // We verify than no new transaction has been broadcast because previously
7708                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7709                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7710                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7711                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7712                 // up bumped justice generation.
7713                 assert_eq!(node_txn.len(), 0);
7714                 node_txn.clear();
7715         }
7716         check_closed_broadcast!(nodes[0], true);
7717         check_added_monitors!(nodes[0], 1);
7718 }
7719
7720 #[test]
7721 fn test_bump_penalty_txn_on_remote_commitment() {
7722         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7723         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7724
7725         // Create 2 HTLCs
7726         // Provide preimage for one
7727         // Check aggregation
7728
7729         let chanmon_cfgs = create_chanmon_cfgs(2);
7730         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7731         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7732         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7733
7734         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7735         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7736         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7737
7738         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7739         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7740         assert_eq!(remote_txn[0].output.len(), 4);
7741         assert_eq!(remote_txn[0].input.len(), 1);
7742         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7743
7744         // Claim a HTLC without revocation (provide B monitor with preimage)
7745         nodes[1].node.claim_funds(payment_preimage);
7746         mine_transaction(&nodes[1], &remote_txn[0]);
7747         check_added_monitors!(nodes[1], 2);
7748         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7749
7750         // One or more claim tx should have been broadcast, check it
7751         let timeout;
7752         let preimage;
7753         let preimage_bump;
7754         let feerate_timeout;
7755         let feerate_preimage;
7756         {
7757                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7758                 // 9 transactions including:
7759                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7760                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7761                 // 2 * HTLC-Success (one RBF bump we'll check later)
7762                 // 1 * HTLC-Timeout
7763                 assert_eq!(node_txn.len(), 8);
7764                 assert_eq!(node_txn[0].input.len(), 1);
7765                 assert_eq!(node_txn[6].input.len(), 1);
7766                 check_spends!(node_txn[0], remote_txn[0]);
7767                 check_spends!(node_txn[6], remote_txn[0]);
7768                 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7769                 preimage_bump = node_txn[3].clone();
7770
7771                 check_spends!(node_txn[1], chan.3);
7772                 check_spends!(node_txn[2], node_txn[1]);
7773                 assert_eq!(node_txn[1], node_txn[4]);
7774                 assert_eq!(node_txn[2], node_txn[5]);
7775
7776                 timeout = node_txn[6].txid();
7777                 let index = node_txn[6].input[0].previous_output.vout;
7778                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7779                 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7780
7781                 preimage = node_txn[0].txid();
7782                 let index = node_txn[0].input[0].previous_output.vout;
7783                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7784                 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7785
7786                 node_txn.clear();
7787         };
7788         assert_ne!(feerate_timeout, 0);
7789         assert_ne!(feerate_preimage, 0);
7790
7791         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7792         connect_blocks(&nodes[1], 15);
7793         {
7794                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7795                 assert_eq!(node_txn.len(), 1);
7796                 assert_eq!(node_txn[0].input.len(), 1);
7797                 assert_eq!(preimage_bump.input.len(), 1);
7798                 check_spends!(node_txn[0], remote_txn[0]);
7799                 check_spends!(preimage_bump, remote_txn[0]);
7800
7801                 let index = preimage_bump.input[0].previous_output.vout;
7802                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7803                 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7804                 assert!(new_feerate * 100 > feerate_timeout * 125);
7805                 assert_ne!(timeout, preimage_bump.txid());
7806
7807                 let index = node_txn[0].input[0].previous_output.vout;
7808                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7809                 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7810                 assert!(new_feerate * 100 > feerate_preimage * 125);
7811                 assert_ne!(preimage, node_txn[0].txid());
7812
7813                 node_txn.clear();
7814         }
7815
7816         nodes[1].node.get_and_clear_pending_events();
7817         nodes[1].node.get_and_clear_pending_msg_events();
7818 }
7819
7820 #[test]
7821 fn test_counterparty_raa_skip_no_crash() {
7822         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7823         // commitment transaction, we would have happily carried on and provided them the next
7824         // commitment transaction based on one RAA forward. This would probably eventually have led to
7825         // channel closure, but it would not have resulted in funds loss. Still, our
7826         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7827         // check simply that the channel is closed in response to such an RAA, but don't check whether
7828         // we decide to punish our counterparty for revoking their funds (as we don't currently
7829         // implement that).
7830         let chanmon_cfgs = create_chanmon_cfgs(2);
7831         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7832         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7833         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7834         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7835
7836         let mut guard = nodes[0].node.channel_state.lock().unwrap();
7837         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7838
7839         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7840
7841         // Make signer believe we got a counterparty signature, so that it allows the revocation
7842         keys.get_enforcement_state().last_holder_commitment -= 1;
7843         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7844
7845         // Must revoke without gaps
7846         keys.get_enforcement_state().last_holder_commitment -= 1;
7847         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7848
7849         keys.get_enforcement_state().last_holder_commitment -= 1;
7850         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7851                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7852
7853         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7854                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7855         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7856         check_added_monitors!(nodes[1], 1);
7857         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7858 }
7859
7860 #[test]
7861 fn test_bump_txn_sanitize_tracking_maps() {
7862         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7863         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7864
7865         let chanmon_cfgs = create_chanmon_cfgs(2);
7866         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7867         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7868         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7869
7870         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7871         // Lock HTLC in both directions
7872         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7873         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7874
7875         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7876         assert_eq!(revoked_local_txn[0].input.len(), 1);
7877         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7878
7879         // Revoke local commitment tx
7880         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7881
7882         // Broadcast set of revoked txn on A
7883         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7884         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7885         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7886
7887         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7888         check_closed_broadcast!(nodes[0], true);
7889         check_added_monitors!(nodes[0], 1);
7890         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7891         let penalty_txn = {
7892                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7893                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7894                 check_spends!(node_txn[0], revoked_local_txn[0]);
7895                 check_spends!(node_txn[1], revoked_local_txn[0]);
7896                 check_spends!(node_txn[2], revoked_local_txn[0]);
7897                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7898                 node_txn.clear();
7899                 penalty_txn
7900         };
7901         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7902         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7903         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7904         {
7905                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7906                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7907                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7908         }
7909 }
7910
7911 #[test]
7912 fn test_override_channel_config() {
7913         let chanmon_cfgs = create_chanmon_cfgs(2);
7914         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7915         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7916         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7917
7918         // Node0 initiates a channel to node1 using the override config.
7919         let mut override_config = UserConfig::default();
7920         override_config.own_channel_config.our_to_self_delay = 200;
7921
7922         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7923
7924         // Assert the channel created by node0 is using the override config.
7925         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7926         assert_eq!(res.channel_flags, 0);
7927         assert_eq!(res.to_self_delay, 200);
7928 }
7929
7930 #[test]
7931 fn test_override_0msat_htlc_minimum() {
7932         let mut zero_config = UserConfig::default();
7933         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
7934         let chanmon_cfgs = create_chanmon_cfgs(2);
7935         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7936         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7937         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7938
7939         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7940         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7941         assert_eq!(res.htlc_minimum_msat, 1);
7942
7943         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
7944         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7945         assert_eq!(res.htlc_minimum_msat, 1);
7946 }
7947
7948 #[test]
7949 fn test_simple_mpp() {
7950         // Simple test of sending a multi-path payment.
7951         let chanmon_cfgs = create_chanmon_cfgs(4);
7952         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7953         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7954         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7955
7956         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7957         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7958         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7959         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7960
7961         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
7962         let path = route.paths[0].clone();
7963         route.paths.push(path);
7964         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7965         route.paths[0][0].short_channel_id = chan_1_id;
7966         route.paths[0][1].short_channel_id = chan_3_id;
7967         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7968         route.paths[1][0].short_channel_id = chan_2_id;
7969         route.paths[1][1].short_channel_id = chan_4_id;
7970         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
7971         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
7972 }
7973
7974 #[test]
7975 fn test_preimage_storage() {
7976         // Simple test of payment preimage storage allowing no client-side storage to claim payments
7977         let chanmon_cfgs = create_chanmon_cfgs(2);
7978         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7979         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7980         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7981
7982         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7983
7984         {
7985                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, 42);
7986                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
7987                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
7988                 check_added_monitors!(nodes[0], 1);
7989                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7990                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7991                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7992                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7993         }
7994         // Note that after leaving the above scope we have no knowledge of any arguments or return
7995         // values from previous calls.
7996         expect_pending_htlcs_forwardable!(nodes[1]);
7997         let events = nodes[1].node.get_and_clear_pending_events();
7998         assert_eq!(events.len(), 1);
7999         match events[0] {
8000                 Event::PaymentReceived { ref purpose, .. } => {
8001                         match &purpose {
8002                                 PaymentPurpose::InvoicePayment { payment_preimage, user_payment_id, .. } => {
8003                                         assert_eq!(*user_payment_id, 42);
8004                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8005                                 },
8006                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8007                         }
8008                 },
8009                 _ => panic!("Unexpected event"),
8010         }
8011 }
8012
8013 #[test]
8014 fn test_secret_timeout() {
8015         // Simple test of payment secret storage time outs
8016         let chanmon_cfgs = create_chanmon_cfgs(2);
8017         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8018         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8019         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8020
8021         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8022
8023         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8024
8025         // We should fail to register the same payment hash twice, at least until we've connected a
8026         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8027         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8028                 assert_eq!(err, "Duplicate payment hash");
8029         } else { panic!(); }
8030         let mut block = {
8031                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8032                 Block {
8033                         header: BlockHeader {
8034                                 version: 0x2000000,
8035                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8036                                 merkle_root: Default::default(),
8037                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8038                         txdata: vec![],
8039                 }
8040         };
8041         connect_block(&nodes[1], &block);
8042         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8043                 assert_eq!(err, "Duplicate payment hash");
8044         } else { panic!(); }
8045
8046         // If we then connect the second block, we should be able to register the same payment hash
8047         // again with a different user_payment_id (this time getting a new payment secret).
8048         block.header.prev_blockhash = block.header.block_hash();
8049         block.header.time += 1;
8050         connect_block(&nodes[1], &block);
8051         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 42).unwrap();
8052         assert_ne!(payment_secret_1, our_payment_secret);
8053
8054         {
8055                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8056                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8057                 check_added_monitors!(nodes[0], 1);
8058                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8059                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8060                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8061                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8062         }
8063         // Note that after leaving the above scope we have no knowledge of any arguments or return
8064         // values from previous calls.
8065         expect_pending_htlcs_forwardable!(nodes[1]);
8066         let events = nodes[1].node.get_and_clear_pending_events();
8067         assert_eq!(events.len(), 1);
8068         match events[0] {
8069                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, user_payment_id }, .. } => {
8070                         assert!(payment_preimage.is_none());
8071                         assert_eq!(user_payment_id, 42);
8072                         assert_eq!(payment_secret, our_payment_secret);
8073                         // We don't actually have the payment preimage with which to claim this payment!
8074                 },
8075                 _ => panic!("Unexpected event"),
8076         }
8077 }
8078
8079 #[test]
8080 fn test_bad_secret_hash() {
8081         // Simple test of unregistered payment hash/invalid payment secret handling
8082         let chanmon_cfgs = create_chanmon_cfgs(2);
8083         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8084         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8085         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8086
8087         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8088
8089         let random_payment_hash = PaymentHash([42; 32]);
8090         let random_payment_secret = PaymentSecret([43; 32]);
8091         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8092         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8093
8094         // All the below cases should end up being handled exactly identically, so we macro the
8095         // resulting events.
8096         macro_rules! handle_unknown_invalid_payment_data {
8097                 () => {
8098                         check_added_monitors!(nodes[0], 1);
8099                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8100                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8101                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8102                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8103
8104                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8105                         // again to process the pending backwards-failure of the HTLC
8106                         expect_pending_htlcs_forwardable!(nodes[1]);
8107                         expect_pending_htlcs_forwardable!(nodes[1]);
8108                         check_added_monitors!(nodes[1], 1);
8109
8110                         // We should fail the payment back
8111                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8112                         match events.pop().unwrap() {
8113                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8114                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8115                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8116                                 },
8117                                 _ => panic!("Unexpected event"),
8118                         }
8119                 }
8120         }
8121
8122         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8123         // Error data is the HTLC value (100,000) and current block height
8124         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8125
8126         // Send a payment with the right payment hash but the wrong payment secret
8127         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8128         handle_unknown_invalid_payment_data!();
8129         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8130
8131         // Send a payment with a random payment hash, but the right payment secret
8132         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8133         handle_unknown_invalid_payment_data!();
8134         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8135
8136         // Send a payment with a random payment hash and random payment secret
8137         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8138         handle_unknown_invalid_payment_data!();
8139         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8140 }
8141
8142 #[test]
8143 fn test_update_err_monitor_lockdown() {
8144         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8145         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8146         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8147         //
8148         // This scenario may happen in a watchtower setup, where watchtower process a block height
8149         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8150         // commitment at same time.
8151
8152         let chanmon_cfgs = create_chanmon_cfgs(2);
8153         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8154         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8155         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8156
8157         // Create some initial channel
8158         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8159         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8160
8161         // Rebalance the network to generate htlc in the two directions
8162         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8163
8164         // Route a HTLC from node 0 to node 1 (but don't settle)
8165         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8166
8167         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8168         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8169         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8170         let persister = test_utils::TestPersister::new();
8171         let watchtower = {
8172                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8173                 let mut w = test_utils::TestVecWriter(Vec::new());
8174                 monitor.write(&mut w).unwrap();
8175                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8176                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8177                 assert!(new_monitor == *monitor);
8178                 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);
8179                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8180                 watchtower
8181         };
8182         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8183         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8184         // transaction lock time requirements here.
8185         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8186         watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8187
8188         // Try to update ChannelMonitor
8189         assert!(nodes[1].node.claim_funds(preimage));
8190         check_added_monitors!(nodes[1], 1);
8191         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8192         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8193         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8194         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8195                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8196                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8197                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8198                 } else { assert!(false); }
8199         } else { assert!(false); };
8200         // Our local monitor is in-sync and hasn't processed yet timeout
8201         check_added_monitors!(nodes[0], 1);
8202         let events = nodes[0].node.get_and_clear_pending_events();
8203         assert_eq!(events.len(), 1);
8204 }
8205
8206 #[test]
8207 fn test_concurrent_monitor_claim() {
8208         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8209         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8210         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8211         // state N+1 confirms. Alice claims output from state N+1.
8212
8213         let chanmon_cfgs = create_chanmon_cfgs(2);
8214         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8215         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8216         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8217
8218         // Create some initial channel
8219         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8220         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8221
8222         // Rebalance the network to generate htlc in the two directions
8223         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8224
8225         // Route a HTLC from node 0 to node 1 (but don't settle)
8226         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8227
8228         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8229         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8230         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8231         let persister = test_utils::TestPersister::new();
8232         let watchtower_alice = {
8233                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8234                 let mut w = test_utils::TestVecWriter(Vec::new());
8235                 monitor.write(&mut w).unwrap();
8236                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8237                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8238                 assert!(new_monitor == *monitor);
8239                 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);
8240                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8241                 watchtower
8242         };
8243         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8244         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8245         // transaction lock time requirements here.
8246         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8247         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8248
8249         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8250         {
8251                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8252                 assert_eq!(txn.len(), 2);
8253                 txn.clear();
8254         }
8255
8256         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8257         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8258         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8259         let persister = test_utils::TestPersister::new();
8260         let watchtower_bob = {
8261                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8262                 let mut w = test_utils::TestVecWriter(Vec::new());
8263                 monitor.write(&mut w).unwrap();
8264                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8265                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8266                 assert!(new_monitor == *monitor);
8267                 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);
8268                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8269                 watchtower
8270         };
8271         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8272         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8273
8274         // Route another payment to generate another update with still previous HTLC pending
8275         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8276         {
8277                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8278         }
8279         check_added_monitors!(nodes[1], 1);
8280
8281         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8282         assert_eq!(updates.update_add_htlcs.len(), 1);
8283         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8284         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8285                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8286                         // Watchtower Alice should already have seen the block and reject the update
8287                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8288                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8289                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8290                 } else { assert!(false); }
8291         } else { assert!(false); };
8292         // Our local monitor is in-sync and hasn't processed yet timeout
8293         check_added_monitors!(nodes[0], 1);
8294
8295         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8296         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8297         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8298
8299         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8300         let bob_state_y;
8301         {
8302                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8303                 assert_eq!(txn.len(), 2);
8304                 bob_state_y = txn[0].clone();
8305                 txn.clear();
8306         };
8307
8308         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8309         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8310         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);
8311         {
8312                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8313                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8314                 // the onchain detection of the HTLC output
8315                 assert_eq!(htlc_txn.len(), 2);
8316                 check_spends!(htlc_txn[0], bob_state_y);
8317                 check_spends!(htlc_txn[1], bob_state_y);
8318         }
8319 }
8320
8321 #[test]
8322 fn test_pre_lockin_no_chan_closed_update() {
8323         // Test that if a peer closes a channel in response to a funding_created message we don't
8324         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8325         // message).
8326         //
8327         // Doing so would imply a channel monitor update before the initial channel monitor
8328         // registration, violating our API guarantees.
8329         //
8330         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8331         // then opening a second channel with the same funding output as the first (which is not
8332         // rejected because the first channel does not exist in the ChannelManager) and closing it
8333         // before receiving funding_signed.
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, None]);
8337         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8338
8339         // Create an initial channel
8340         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8341         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8342         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8343         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8344         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8345
8346         // Move the first channel through the funding flow...
8347         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8348
8349         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8350         check_added_monitors!(nodes[0], 0);
8351
8352         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8353         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8354         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8355         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8356         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8357 }
8358
8359 #[test]
8360 fn test_htlc_no_detection() {
8361         // This test is a mutation to underscore the detection logic bug we had
8362         // before #653. HTLC value routed is above the remaining balance, thus
8363         // inverting HTLC and `to_remote` output. HTLC will come second and
8364         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8365         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8366         // outputs order detection for correct spending children filtring.
8367
8368         let chanmon_cfgs = create_chanmon_cfgs(2);
8369         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8370         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8371         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8372
8373         // Create some initial channels
8374         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8375
8376         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8377         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8378         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8379         assert_eq!(local_txn[0].input.len(), 1);
8380         assert_eq!(local_txn[0].output.len(), 3);
8381         check_spends!(local_txn[0], chan_1.3);
8382
8383         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8384         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8385         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8386         // We deliberately connect the local tx twice as this should provoke a failure calling
8387         // this test before #653 fix.
8388         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);
8389         check_closed_broadcast!(nodes[0], true);
8390         check_added_monitors!(nodes[0], 1);
8391         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8392         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8393
8394         let htlc_timeout = {
8395                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8396                 assert_eq!(node_txn[1].input.len(), 1);
8397                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8398                 check_spends!(node_txn[1], local_txn[0]);
8399                 node_txn[1].clone()
8400         };
8401
8402         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8403         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8404         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8405         expect_payment_failed!(nodes[0], our_payment_hash, true);
8406 }
8407
8408 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8409         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8410         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8411         // Carol, Alice would be the upstream node, and Carol the downstream.)
8412         //
8413         // Steps of the test:
8414         // 1) Alice sends a HTLC to Carol through Bob.
8415         // 2) Carol doesn't settle the HTLC.
8416         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8417         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8418         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8419         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8420         // 5) Carol release the preimage to Bob off-chain.
8421         // 6) Bob claims the offered output on the broadcasted commitment.
8422         let chanmon_cfgs = create_chanmon_cfgs(3);
8423         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8424         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8425         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8426
8427         // Create some initial channels
8428         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8429         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8430
8431         // Steps (1) and (2):
8432         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8433         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8434
8435         // Check that Alice's commitment transaction now contains an output for this HTLC.
8436         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8437         check_spends!(alice_txn[0], chan_ab.3);
8438         assert_eq!(alice_txn[0].output.len(), 2);
8439         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8440         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8441         assert_eq!(alice_txn.len(), 2);
8442
8443         // Steps (3) and (4):
8444         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8445         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8446         let mut force_closing_node = 0; // Alice force-closes
8447         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8448         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8449         check_closed_broadcast!(nodes[force_closing_node], true);
8450         check_added_monitors!(nodes[force_closing_node], 1);
8451         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8452         if go_onchain_before_fulfill {
8453                 let txn_to_broadcast = match broadcast_alice {
8454                         true => alice_txn.clone(),
8455                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8456                 };
8457                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8458                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8459                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8460                 if broadcast_alice {
8461                         check_closed_broadcast!(nodes[1], true);
8462                         check_added_monitors!(nodes[1], 1);
8463                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8464                 }
8465                 assert_eq!(bob_txn.len(), 1);
8466                 check_spends!(bob_txn[0], chan_ab.3);
8467         }
8468
8469         // Step (5):
8470         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8471         // process of removing the HTLC from their commitment transactions.
8472         assert!(nodes[2].node.claim_funds(payment_preimage));
8473         check_added_monitors!(nodes[2], 1);
8474         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8475         assert!(carol_updates.update_add_htlcs.is_empty());
8476         assert!(carol_updates.update_fail_htlcs.is_empty());
8477         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8478         assert!(carol_updates.update_fee.is_none());
8479         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8480
8481         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8482         expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8483         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8484         if !go_onchain_before_fulfill && broadcast_alice {
8485                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8486                 assert_eq!(events.len(), 1);
8487                 match events[0] {
8488                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8489                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8490                         },
8491                         _ => panic!("Unexpected event"),
8492                 };
8493         }
8494         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8495         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8496         // Carol<->Bob's updated commitment transaction info.
8497         check_added_monitors!(nodes[1], 2);
8498
8499         let events = nodes[1].node.get_and_clear_pending_msg_events();
8500         assert_eq!(events.len(), 2);
8501         let bob_revocation = match events[0] {
8502                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8503                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8504                         (*msg).clone()
8505                 },
8506                 _ => panic!("Unexpected event"),
8507         };
8508         let bob_updates = match events[1] {
8509                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8510                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8511                         (*updates).clone()
8512                 },
8513                 _ => panic!("Unexpected event"),
8514         };
8515
8516         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8517         check_added_monitors!(nodes[2], 1);
8518         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8519         check_added_monitors!(nodes[2], 1);
8520
8521         let events = nodes[2].node.get_and_clear_pending_msg_events();
8522         assert_eq!(events.len(), 1);
8523         let carol_revocation = match events[0] {
8524                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8525                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8526                         (*msg).clone()
8527                 },
8528                 _ => panic!("Unexpected event"),
8529         };
8530         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8531         check_added_monitors!(nodes[1], 1);
8532
8533         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8534         // here's where we put said channel's commitment tx on-chain.
8535         let mut txn_to_broadcast = alice_txn.clone();
8536         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8537         if !go_onchain_before_fulfill {
8538                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8539                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8540                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8541                 if broadcast_alice {
8542                         check_closed_broadcast!(nodes[1], true);
8543                         check_added_monitors!(nodes[1], 1);
8544                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8545                 }
8546                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8547                 if broadcast_alice {
8548                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8549                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8550                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8551                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8552                         // broadcasted.
8553                         assert_eq!(bob_txn.len(), 3);
8554                         check_spends!(bob_txn[1], chan_ab.3);
8555                 } else {
8556                         assert_eq!(bob_txn.len(), 2);
8557                         check_spends!(bob_txn[0], chan_ab.3);
8558                 }
8559         }
8560
8561         // Step (6):
8562         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8563         // broadcasted commitment transaction.
8564         {
8565                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8566                 if go_onchain_before_fulfill {
8567                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8568                         assert_eq!(bob_txn.len(), 2);
8569                 }
8570                 let script_weight = match broadcast_alice {
8571                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8572                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8573                 };
8574                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8575                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8576                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8577                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8578                 if broadcast_alice && !go_onchain_before_fulfill {
8579                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8580                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8581                 } else {
8582                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8583                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8584                 }
8585         }
8586 }
8587
8588 #[test]
8589 fn test_onchain_htlc_settlement_after_close() {
8590         do_test_onchain_htlc_settlement_after_close(true, true);
8591         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8592         do_test_onchain_htlc_settlement_after_close(true, false);
8593         do_test_onchain_htlc_settlement_after_close(false, false);
8594 }
8595
8596 #[test]
8597 fn test_duplicate_chan_id() {
8598         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8599         // already open we reject it and keep the old channel.
8600         //
8601         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8602         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8603         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8604         // updating logic for the existing channel.
8605         let chanmon_cfgs = create_chanmon_cfgs(2);
8606         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8607         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8608         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8609
8610         // Create an initial channel
8611         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8612         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8613         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8614         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()));
8615
8616         // Try to create a second channel with the same temporary_channel_id as the first and check
8617         // that it is rejected.
8618         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8619         {
8620                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8621                 assert_eq!(events.len(), 1);
8622                 match events[0] {
8623                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8624                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8625                                 // first (valid) and second (invalid) channels are closed, given they both have
8626                                 // the same non-temporary channel_id. However, currently we do not, so we just
8627                                 // move forward with it.
8628                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8629                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8630                         },
8631                         _ => panic!("Unexpected event"),
8632                 }
8633         }
8634
8635         // Move the first channel through the funding flow...
8636         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8637
8638         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8639         check_added_monitors!(nodes[0], 0);
8640
8641         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8642         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8643         {
8644                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8645                 assert_eq!(added_monitors.len(), 1);
8646                 assert_eq!(added_monitors[0].0, funding_output);
8647                 added_monitors.clear();
8648         }
8649         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8650
8651         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8652         let channel_id = funding_outpoint.to_channel_id();
8653
8654         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8655         // temporary one).
8656
8657         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8658         // Technically this is allowed by the spec, but we don't support it and there's little reason
8659         // to. Still, it shouldn't cause any other issues.
8660         open_chan_msg.temporary_channel_id = channel_id;
8661         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8662         {
8663                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8664                 assert_eq!(events.len(), 1);
8665                 match events[0] {
8666                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8667                                 // Technically, at this point, nodes[1] would be justified in thinking both
8668                                 // channels are closed, but currently we do not, so we just move forward with it.
8669                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8670                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8671                         },
8672                         _ => panic!("Unexpected event"),
8673                 }
8674         }
8675
8676         // Now try to create a second channel which has a duplicate funding output.
8677         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8678         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8679         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8680         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()));
8681         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8682
8683         let funding_created = {
8684                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8685                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8686                 let logger = test_utils::TestLogger::new();
8687                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8688         };
8689         check_added_monitors!(nodes[0], 0);
8690         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8691         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8692         // still needs to be cleared here.
8693         check_added_monitors!(nodes[1], 1);
8694
8695         // ...still, nodes[1] will reject the duplicate channel.
8696         {
8697                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8698                 assert_eq!(events.len(), 1);
8699                 match events[0] {
8700                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8701                                 // Technically, at this point, nodes[1] would be justified in thinking both
8702                                 // channels are closed, but currently we do not, so we just move forward with it.
8703                                 assert_eq!(msg.channel_id, channel_id);
8704                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8705                         },
8706                         _ => panic!("Unexpected event"),
8707                 }
8708         }
8709
8710         // finally, finish creating the original channel and send a payment over it to make sure
8711         // everything is functional.
8712         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8713         {
8714                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8715                 assert_eq!(added_monitors.len(), 1);
8716                 assert_eq!(added_monitors[0].0, funding_output);
8717                 added_monitors.clear();
8718         }
8719
8720         let events_4 = nodes[0].node.get_and_clear_pending_events();
8721         assert_eq!(events_4.len(), 0);
8722         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8723         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8724
8725         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8726         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8727         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8728         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8729 }
8730
8731 #[test]
8732 fn test_error_chans_closed() {
8733         // Test that we properly handle error messages, closing appropriate channels.
8734         //
8735         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8736         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8737         // we can test various edge cases around it to ensure we don't regress.
8738         let chanmon_cfgs = create_chanmon_cfgs(3);
8739         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8740         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8741         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8742
8743         // Create some initial channels
8744         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8745         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8746         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8747
8748         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8749         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8750         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8751
8752         // Closing a channel from a different peer has no effect
8753         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8754         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8755
8756         // Closing one channel doesn't impact others
8757         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8758         check_added_monitors!(nodes[0], 1);
8759         check_closed_broadcast!(nodes[0], false);
8760         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8761         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8762         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8763         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);
8764         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);
8765
8766         // A null channel ID should close all channels
8767         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8768         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8769         check_added_monitors!(nodes[0], 2);
8770         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8771         let events = nodes[0].node.get_and_clear_pending_msg_events();
8772         assert_eq!(events.len(), 2);
8773         match events[0] {
8774                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8775                         assert_eq!(msg.contents.flags & 2, 2);
8776                 },
8777                 _ => panic!("Unexpected event"),
8778         }
8779         match events[1] {
8780                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8781                         assert_eq!(msg.contents.flags & 2, 2);
8782                 },
8783                 _ => panic!("Unexpected event"),
8784         }
8785         // Note that at this point users of a standard PeerHandler will end up calling
8786         // peer_disconnected with no_connection_possible set to false, duplicating the
8787         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8788         // users with their own peer handling logic. We duplicate the call here, however.
8789         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8790         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8791
8792         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8793         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8794         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8795 }
8796
8797 #[test]
8798 fn test_invalid_funding_tx() {
8799         // Test that we properly handle invalid funding transactions sent to us from a peer.
8800         //
8801         // Previously, all other major lightning implementations had failed to properly sanitize
8802         // funding transactions from their counterparties, leading to a multi-implementation critical
8803         // security vulnerability (though we always sanitized properly, we've previously had
8804         // un-released crashes in the sanitization process).
8805         let chanmon_cfgs = create_chanmon_cfgs(2);
8806         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8807         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8808         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8809
8810         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8811         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()));
8812         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()));
8813
8814         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
8815         for output in tx.output.iter_mut() {
8816                 // Make the confirmed funding transaction have a bogus script_pubkey
8817                 output.script_pubkey = bitcoin::Script::new();
8818         }
8819
8820         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
8821         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()));
8822         check_added_monitors!(nodes[1], 1);
8823
8824         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()));
8825         check_added_monitors!(nodes[0], 1);
8826
8827         let events_1 = nodes[0].node.get_and_clear_pending_events();
8828         assert_eq!(events_1.len(), 0);
8829
8830         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8831         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8832         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8833
8834         confirm_transaction_at(&nodes[1], &tx, 1);
8835         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8836         check_added_monitors!(nodes[1], 1);
8837         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8838         assert_eq!(events_2.len(), 1);
8839         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8840                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8841                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8842                         assert_eq!(msg.data, "funding tx had wrong script/value or output index");
8843                 } else { panic!(); }
8844         } else { panic!(); }
8845         assert_eq!(nodes[1].node.list_channels().len(), 0);
8846 }
8847
8848 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8849         // In the first version of the chain::Confirm interface, after a refactor was made to not
8850         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8851         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8852         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8853         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8854         // spending transaction until height N+1 (or greater). This was due to the way
8855         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8856         // spending transaction at the height the input transaction was confirmed at, not whether we
8857         // should broadcast a spending transaction at the current height.
8858         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8859         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8860         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
8861         // until we learned about an additional block.
8862         //
8863         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
8864         // aren't broadcasting transactions too early (ie not broadcasting them at all).
8865         let chanmon_cfgs = create_chanmon_cfgs(3);
8866         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8867         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8868         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8869         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
8870
8871         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8872         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8873         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
8874         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
8875         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8876
8877         nodes[1].node.force_close_channel(&channel_id).unwrap();
8878         check_closed_broadcast!(nodes[1], true);
8879         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8880         check_added_monitors!(nodes[1], 1);
8881         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8882         assert_eq!(node_txn.len(), 1);
8883
8884         let conf_height = nodes[1].best_block_info().1;
8885         if !test_height_before_timelock {
8886                 connect_blocks(&nodes[1], 24 * 6);
8887         }
8888         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8889                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
8890         if test_height_before_timelock {
8891                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
8892                 // generate any events or broadcast any transactions
8893                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8894                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
8895         } else {
8896                 // We should broadcast an HTLC transaction spending our funding transaction first
8897                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8898                 assert_eq!(spending_txn.len(), 2);
8899                 assert_eq!(spending_txn[0], node_txn[0]);
8900                 check_spends!(spending_txn[1], node_txn[0]);
8901                 // We should also generate a SpendableOutputs event with the to_self output (as its
8902                 // timelock is up).
8903                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
8904                 assert_eq!(descriptor_spend_txn.len(), 1);
8905
8906                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
8907                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
8908                 // additional block built on top of the current chain.
8909                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8910                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
8911                 expect_pending_htlcs_forwardable!(nodes[1]);
8912                 check_added_monitors!(nodes[1], 1);
8913
8914                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8915                 assert!(updates.update_add_htlcs.is_empty());
8916                 assert!(updates.update_fulfill_htlcs.is_empty());
8917                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8918                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8919                 assert!(updates.update_fee.is_none());
8920                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
8921                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
8922                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
8923         }
8924 }
8925
8926 #[test]
8927 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
8928         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
8929         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
8930 }
8931
8932 #[test]
8933 fn test_forwardable_regen() {
8934         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
8935         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
8936         // HTLCs.
8937         // We test it for both payment receipt and payment forwarding.
8938
8939         let chanmon_cfgs = create_chanmon_cfgs(3);
8940         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8941         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8942         let persister: test_utils::TestPersister;
8943         let new_chain_monitor: test_utils::TestChainMonitor;
8944         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
8945         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8946         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8947         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
8948
8949         // First send a payment to nodes[1]
8950         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8951         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8952         check_added_monitors!(nodes[0], 1);
8953
8954         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8955         assert_eq!(events.len(), 1);
8956         let payment_event = SendEvent::from_event(events.pop().unwrap());
8957         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8958         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8959
8960         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
8961
8962         // Next send a payment which is forwarded by nodes[1]
8963         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
8964         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
8965         check_added_monitors!(nodes[0], 1);
8966
8967         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8968         assert_eq!(events.len(), 1);
8969         let payment_event = SendEvent::from_event(events.pop().unwrap());
8970         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8971         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8972
8973         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
8974         // generated
8975         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8976
8977         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
8978         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8979         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8980
8981         let nodes_1_serialized = nodes[1].node.encode();
8982         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
8983         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
8984         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
8985         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
8986
8987         persister = test_utils::TestPersister::new();
8988         let keys_manager = &chanmon_cfgs[1].keys_manager;
8989         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);
8990         nodes[1].chain_monitor = &new_chain_monitor;
8991
8992         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8993         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
8994                 &mut chan_0_monitor_read, keys_manager).unwrap();
8995         assert!(chan_0_monitor_read.is_empty());
8996         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
8997         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
8998                 &mut chan_1_monitor_read, keys_manager).unwrap();
8999         assert!(chan_1_monitor_read.is_empty());
9000
9001         let mut nodes_1_read = &nodes_1_serialized[..];
9002         let (_, nodes_1_deserialized_tmp) = {
9003                 let mut channel_monitors = HashMap::new();
9004                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9005                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9006                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9007                         default_config: UserConfig::default(),
9008                         keys_manager,
9009                         fee_estimator: node_cfgs[1].fee_estimator,
9010                         chain_monitor: nodes[1].chain_monitor,
9011                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9012                         logger: nodes[1].logger,
9013                         channel_monitors,
9014                 }).unwrap()
9015         };
9016         nodes_1_deserialized = nodes_1_deserialized_tmp;
9017         assert!(nodes_1_read.is_empty());
9018
9019         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9020         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9021         nodes[1].node = &nodes_1_deserialized;
9022         check_added_monitors!(nodes[1], 2);
9023
9024         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9025         // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9026         // the commitment state.
9027         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9028
9029         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9030
9031         expect_pending_htlcs_forwardable!(nodes[1]);
9032         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9033         check_added_monitors!(nodes[1], 1);
9034
9035         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9036         assert_eq!(events.len(), 1);
9037         let payment_event = SendEvent::from_event(events.pop().unwrap());
9038         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9039         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9040         expect_pending_htlcs_forwardable!(nodes[2]);
9041         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9042
9043         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9044         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9045 }
9046
9047 #[test]
9048 fn test_keysend_payments_to_public_node() {
9049         let chanmon_cfgs = create_chanmon_cfgs(2);
9050         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9051         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9052         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9053
9054         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9055         let network_graph = nodes[0].network_graph;
9056         let payer_pubkey = nodes[0].node.get_our_node_id();
9057         let payee_pubkey = nodes[1].node.get_our_node_id();
9058         let params = RouteParameters {
9059                 payee: Payee::for_keysend(payee_pubkey),
9060                 final_value_msat: 10000,
9061                 final_cltv_expiry_delta: 40,
9062         };
9063         let scorer = test_utils::TestScorer::with_fixed_penalty(0);
9064         let route = find_route(&payer_pubkey, &params, network_graph, None, nodes[0].logger, &scorer).unwrap();
9065
9066         let test_preimage = PaymentPreimage([42; 32]);
9067         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9068         check_added_monitors!(nodes[0], 1);
9069         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9070         assert_eq!(events.len(), 1);
9071         let event = events.pop().unwrap();
9072         let path = vec![&nodes[1]];
9073         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9074         claim_payment(&nodes[0], &path, test_preimage);
9075 }
9076
9077 #[test]
9078 fn test_keysend_payments_to_private_node() {
9079         let chanmon_cfgs = create_chanmon_cfgs(2);
9080         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9081         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9082         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9083
9084         let payer_pubkey = nodes[0].node.get_our_node_id();
9085         let payee_pubkey = nodes[1].node.get_our_node_id();
9086         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9087         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9088
9089         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9090         let params = RouteParameters {
9091                 payee: Payee::for_keysend(payee_pubkey),
9092                 final_value_msat: 10000,
9093                 final_cltv_expiry_delta: 40,
9094         };
9095         let network_graph = nodes[0].network_graph;
9096         let first_hops = nodes[0].node.list_usable_channels();
9097         let scorer = test_utils::TestScorer::with_fixed_penalty(0);
9098         let route = find_route(
9099                 &payer_pubkey, &params, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9100                 nodes[0].logger, &scorer
9101         ).unwrap();
9102
9103         let test_preimage = PaymentPreimage([42; 32]);
9104         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9105         check_added_monitors!(nodes[0], 1);
9106         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9107         assert_eq!(events.len(), 1);
9108         let event = events.pop().unwrap();
9109         let path = vec![&nodes[1]];
9110         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9111         claim_payment(&nodes[0], &path, test_preimage);
9112 }