Replace get_route with get_route_and_payment_hash
[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::{Route, RouteHop, RouteHint, RouteHintHop, get_route, get_keysend_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::{Txid, 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] }, &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] }, &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.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
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.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
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                 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3272                 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3273                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3274         }
3275         mine_transaction(&nodes[2], &tx);
3276         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3277         assert_eq!(node_txn.len(), 1);
3278         assert_eq!(node_txn[0].input.len(), 1);
3279         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3280         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3281         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3282
3283         check_spends!(node_txn[0], tx);
3284 }
3285
3286 #[test]
3287 fn test_dup_events_on_peer_disconnect() {
3288         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3289         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3290         // as we used to generate the event immediately upon receipt of the payment preimage in the
3291         // update_fulfill_htlc message.
3292
3293         let chanmon_cfgs = create_chanmon_cfgs(2);
3294         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3295         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3296         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3297         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3298
3299         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3300
3301         assert!(nodes[1].node.claim_funds(payment_preimage));
3302         check_added_monitors!(nodes[1], 1);
3303         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3304         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3305         expect_payment_sent!(nodes[0], payment_preimage);
3306
3307         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3308         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3309
3310         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3311         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3312 }
3313
3314 #[test]
3315 fn test_simple_peer_disconnect() {
3316         // Test that we can reconnect when there are no lost messages
3317         let chanmon_cfgs = create_chanmon_cfgs(3);
3318         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3319         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3320         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3321         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3322         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3323
3324         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3325         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3326         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3327
3328         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3329         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3330         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3331         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3332
3333         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3334         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3335         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3336
3337         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3338         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3339         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3340         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3341
3342         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3343         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3344
3345         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3346         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3347
3348         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3349         {
3350                 let events = nodes[0].node.get_and_clear_pending_events();
3351                 assert_eq!(events.len(), 2);
3352                 match events[0] {
3353                         Event::PaymentSent { payment_preimage, payment_hash } => {
3354                                 assert_eq!(payment_preimage, payment_preimage_3);
3355                                 assert_eq!(payment_hash, payment_hash_3);
3356                         },
3357                         _ => panic!("Unexpected event"),
3358                 }
3359                 match events[1] {
3360                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3361                                 assert_eq!(payment_hash, payment_hash_5);
3362                                 assert!(rejected_by_dest);
3363                         },
3364                         _ => panic!("Unexpected event"),
3365                 }
3366         }
3367
3368         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3369         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3370 }
3371
3372 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3373         // Test that we can reconnect when in-flight HTLC updates get dropped
3374         let chanmon_cfgs = create_chanmon_cfgs(2);
3375         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3376         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3377         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3378
3379         let mut as_funding_locked = None;
3380         if messages_delivered == 0 {
3381                 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3382                 as_funding_locked = Some(funding_locked);
3383                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3384                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3385                 // it before the channel_reestablish message.
3386         } else {
3387                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3388         }
3389
3390         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3391
3392         let payment_event = {
3393                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3394                 check_added_monitors!(nodes[0], 1);
3395
3396                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3397                 assert_eq!(events.len(), 1);
3398                 SendEvent::from_event(events.remove(0))
3399         };
3400         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3401
3402         if messages_delivered < 2 {
3403                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3404         } else {
3405                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3406                 if messages_delivered >= 3 {
3407                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3408                         check_added_monitors!(nodes[1], 1);
3409                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3410
3411                         if messages_delivered >= 4 {
3412                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3413                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3414                                 check_added_monitors!(nodes[0], 1);
3415
3416                                 if messages_delivered >= 5 {
3417                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3418                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3419                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3420                                         check_added_monitors!(nodes[0], 1);
3421
3422                                         if messages_delivered >= 6 {
3423                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3424                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3425                                                 check_added_monitors!(nodes[1], 1);
3426                                         }
3427                                 }
3428                         }
3429                 }
3430         }
3431
3432         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3433         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3434         if messages_delivered < 3 {
3435                 if simulate_broken_lnd {
3436                         // lnd has a long-standing bug where they send a funding_locked prior to a
3437                         // channel_reestablish if you reconnect prior to funding_locked time.
3438                         //
3439                         // Here we simulate that behavior, delivering a funding_locked immediately on
3440                         // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3441                         // in `reconnect_nodes` but we currently don't fail based on that.
3442                         //
3443                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3444                         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3445                 }
3446                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3447                 // received on either side, both sides will need to resend them.
3448                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3449         } else if messages_delivered == 3 {
3450                 // nodes[0] still wants its RAA + commitment_signed
3451                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3452         } else if messages_delivered == 4 {
3453                 // nodes[0] still wants its commitment_signed
3454                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3455         } else if messages_delivered == 5 {
3456                 // nodes[1] still wants its final RAA
3457                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3458         } else if messages_delivered == 6 {
3459                 // Everything was delivered...
3460                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3461         }
3462
3463         let events_1 = nodes[1].node.get_and_clear_pending_events();
3464         assert_eq!(events_1.len(), 1);
3465         match events_1[0] {
3466                 Event::PendingHTLCsForwardable { .. } => { },
3467                 _ => panic!("Unexpected event"),
3468         };
3469
3470         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3471         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3472         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3473
3474         nodes[1].node.process_pending_htlc_forwards();
3475
3476         let events_2 = nodes[1].node.get_and_clear_pending_events();
3477         assert_eq!(events_2.len(), 1);
3478         match events_2[0] {
3479                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3480                         assert_eq!(payment_hash_1, *payment_hash);
3481                         assert_eq!(amt, 1000000);
3482                         match &purpose {
3483                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3484                                         assert!(payment_preimage.is_none());
3485                                         assert_eq!(payment_secret_1, *payment_secret);
3486                                 },
3487                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3488                         }
3489                 },
3490                 _ => panic!("Unexpected event"),
3491         }
3492
3493         nodes[1].node.claim_funds(payment_preimage_1);
3494         check_added_monitors!(nodes[1], 1);
3495
3496         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3497         assert_eq!(events_3.len(), 1);
3498         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3499                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3500                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3501                         assert!(updates.update_add_htlcs.is_empty());
3502                         assert!(updates.update_fail_htlcs.is_empty());
3503                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3504                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3505                         assert!(updates.update_fee.is_none());
3506                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3507                 },
3508                 _ => panic!("Unexpected event"),
3509         };
3510
3511         if messages_delivered >= 1 {
3512                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3513
3514                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3515                 assert_eq!(events_4.len(), 1);
3516                 match events_4[0] {
3517                         Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3518                                 assert_eq!(payment_preimage_1, *payment_preimage);
3519                                 assert_eq!(payment_hash_1, *payment_hash);
3520                         },
3521                         _ => panic!("Unexpected event"),
3522                 }
3523
3524                 if messages_delivered >= 2 {
3525                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3526                         check_added_monitors!(nodes[0], 1);
3527                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3528
3529                         if messages_delivered >= 3 {
3530                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3531                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3532                                 check_added_monitors!(nodes[1], 1);
3533
3534                                 if messages_delivered >= 4 {
3535                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3536                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3537                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3538                                         check_added_monitors!(nodes[1], 1);
3539
3540                                         if messages_delivered >= 5 {
3541                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3542                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3543                                                 check_added_monitors!(nodes[0], 1);
3544                                         }
3545                                 }
3546                         }
3547                 }
3548         }
3549
3550         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3551         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3552         if messages_delivered < 2 {
3553                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3554                 if messages_delivered < 1 {
3555                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3556                         assert_eq!(events_4.len(), 1);
3557                         match events_4[0] {
3558                                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3559                                         assert_eq!(payment_preimage_1, *payment_preimage);
3560                                         assert_eq!(payment_hash_1, *payment_hash);
3561                                 },
3562                                 _ => panic!("Unexpected event"),
3563                         }
3564                 } else {
3565                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3566                 }
3567         } else if messages_delivered == 2 {
3568                 // nodes[0] still wants its RAA + commitment_signed
3569                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3570         } else if messages_delivered == 3 {
3571                 // nodes[0] still wants its commitment_signed
3572                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3573         } else if messages_delivered == 4 {
3574                 // nodes[1] still wants its final RAA
3575                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3576         } else if messages_delivered == 5 {
3577                 // Everything was delivered...
3578                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3579         }
3580
3581         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3582         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3583         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3584
3585         // Channel should still work fine...
3586         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3587         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3588         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3589 }
3590
3591 #[test]
3592 fn test_drop_messages_peer_disconnect_a() {
3593         do_test_drop_messages_peer_disconnect(0, true);
3594         do_test_drop_messages_peer_disconnect(0, false);
3595         do_test_drop_messages_peer_disconnect(1, false);
3596         do_test_drop_messages_peer_disconnect(2, false);
3597 }
3598
3599 #[test]
3600 fn test_drop_messages_peer_disconnect_b() {
3601         do_test_drop_messages_peer_disconnect(3, false);
3602         do_test_drop_messages_peer_disconnect(4, false);
3603         do_test_drop_messages_peer_disconnect(5, false);
3604         do_test_drop_messages_peer_disconnect(6, false);
3605 }
3606
3607 #[test]
3608 fn test_funding_peer_disconnect() {
3609         // Test that we can lock in our funding tx while disconnected
3610         let chanmon_cfgs = create_chanmon_cfgs(2);
3611         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3612         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3613         let persister: test_utils::TestPersister;
3614         let new_chain_monitor: test_utils::TestChainMonitor;
3615         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3616         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3617         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3618
3619         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3620         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3621
3622         confirm_transaction(&nodes[0], &tx);
3623         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3624         assert_eq!(events_1.len(), 1);
3625         match events_1[0] {
3626                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3627                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3628                 },
3629                 _ => panic!("Unexpected event"),
3630         }
3631
3632         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3633
3634         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3635         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3636
3637         confirm_transaction(&nodes[1], &tx);
3638         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3639         assert_eq!(events_2.len(), 2);
3640         let funding_locked = match events_2[0] {
3641                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3642                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3643                         msg.clone()
3644                 },
3645                 _ => panic!("Unexpected event"),
3646         };
3647         let bs_announcement_sigs = match events_2[1] {
3648                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3649                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3650                         msg.clone()
3651                 },
3652                 _ => panic!("Unexpected event"),
3653         };
3654
3655         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3656
3657         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3658         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3659         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3660         assert_eq!(events_3.len(), 2);
3661         let as_announcement_sigs = match events_3[0] {
3662                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3663                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3664                         msg.clone()
3665                 },
3666                 _ => panic!("Unexpected event"),
3667         };
3668         let (as_announcement, as_update) = match events_3[1] {
3669                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3670                         (msg.clone(), update_msg.clone())
3671                 },
3672                 _ => panic!("Unexpected event"),
3673         };
3674
3675         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3676         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3677         assert_eq!(events_4.len(), 1);
3678         let (_, bs_update) = match events_4[0] {
3679                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3680                         (msg.clone(), update_msg.clone())
3681                 },
3682                 _ => panic!("Unexpected event"),
3683         };
3684
3685         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3686         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3687         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3688
3689         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3690         let (payment_preimage, _, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3691         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3692
3693         // Check that after deserialization and reconnection we can still generate an identical
3694         // channel_announcement from the cached signatures.
3695         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3696
3697         let nodes_0_serialized = nodes[0].node.encode();
3698         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3699         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
3700
3701         persister = test_utils::TestPersister::new();
3702         let keys_manager = &chanmon_cfgs[0].keys_manager;
3703         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);
3704         nodes[0].chain_monitor = &new_chain_monitor;
3705         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3706         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3707                 &mut chan_0_monitor_read, keys_manager).unwrap();
3708         assert!(chan_0_monitor_read.is_empty());
3709
3710         let mut nodes_0_read = &nodes_0_serialized[..];
3711         let (_, nodes_0_deserialized_tmp) = {
3712                 let mut channel_monitors = HashMap::new();
3713                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3714                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3715                         default_config: UserConfig::default(),
3716                         keys_manager,
3717                         fee_estimator: node_cfgs[0].fee_estimator,
3718                         chain_monitor: nodes[0].chain_monitor,
3719                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3720                         logger: nodes[0].logger,
3721                         channel_monitors,
3722                 }).unwrap()
3723         };
3724         nodes_0_deserialized = nodes_0_deserialized_tmp;
3725         assert!(nodes_0_read.is_empty());
3726
3727         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3728         nodes[0].node = &nodes_0_deserialized;
3729         check_added_monitors!(nodes[0], 1);
3730
3731         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3732
3733         // as_announcement should be re-generated exactly by broadcast_node_announcement.
3734         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3735         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3736         let mut found_announcement = false;
3737         for event in msgs.iter() {
3738                 match event {
3739                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3740                                 if *msg == as_announcement { found_announcement = true; }
3741                         },
3742                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3743                         _ => panic!("Unexpected event"),
3744                 }
3745         }
3746         assert!(found_announcement);
3747 }
3748
3749 #[test]
3750 fn test_drop_messages_peer_disconnect_dual_htlc() {
3751         // Test that we can handle reconnecting when both sides of a channel have pending
3752         // commitment_updates when we disconnect.
3753         let chanmon_cfgs = create_chanmon_cfgs(2);
3754         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3755         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3756         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3757         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3758
3759         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3760
3761         // Now try to send a second payment which will fail to send
3762         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3763         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3764         check_added_monitors!(nodes[0], 1);
3765
3766         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3767         assert_eq!(events_1.len(), 1);
3768         match events_1[0] {
3769                 MessageSendEvent::UpdateHTLCs { .. } => {},
3770                 _ => panic!("Unexpected event"),
3771         }
3772
3773         assert!(nodes[1].node.claim_funds(payment_preimage_1));
3774         check_added_monitors!(nodes[1], 1);
3775
3776         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3777         assert_eq!(events_2.len(), 1);
3778         match events_2[0] {
3779                 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 } } => {
3780                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3781                         assert!(update_add_htlcs.is_empty());
3782                         assert_eq!(update_fulfill_htlcs.len(), 1);
3783                         assert!(update_fail_htlcs.is_empty());
3784                         assert!(update_fail_malformed_htlcs.is_empty());
3785                         assert!(update_fee.is_none());
3786
3787                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3788                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3789                         assert_eq!(events_3.len(), 1);
3790                         match events_3[0] {
3791                                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3792                                         assert_eq!(*payment_preimage, payment_preimage_1);
3793                                         assert_eq!(*payment_hash, payment_hash_1);
3794                                 },
3795                                 _ => panic!("Unexpected event"),
3796                         }
3797
3798                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3799                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3800                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3801                         check_added_monitors!(nodes[0], 1);
3802                 },
3803                 _ => panic!("Unexpected event"),
3804         }
3805
3806         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3807         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3808
3809         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3810         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3811         assert_eq!(reestablish_1.len(), 1);
3812         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3813         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3814         assert_eq!(reestablish_2.len(), 1);
3815
3816         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3817         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3818         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3819         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3820
3821         assert!(as_resp.0.is_none());
3822         assert!(bs_resp.0.is_none());
3823
3824         assert!(bs_resp.1.is_none());
3825         assert!(bs_resp.2.is_none());
3826
3827         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3828
3829         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3830         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3831         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3832         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3833         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3834         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3835         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3836         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3837         // No commitment_signed so get_event_msg's assert(len == 1) passes
3838         check_added_monitors!(nodes[1], 1);
3839
3840         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3841         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3842         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3843         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3844         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3845         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3846         assert!(bs_second_commitment_signed.update_fee.is_none());
3847         check_added_monitors!(nodes[1], 1);
3848
3849         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3850         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3851         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3852         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3853         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3854         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3855         assert!(as_commitment_signed.update_fee.is_none());
3856         check_added_monitors!(nodes[0], 1);
3857
3858         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3859         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3860         // No commitment_signed so get_event_msg's assert(len == 1) passes
3861         check_added_monitors!(nodes[0], 1);
3862
3863         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3864         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3865         // No commitment_signed so get_event_msg's assert(len == 1) passes
3866         check_added_monitors!(nodes[1], 1);
3867
3868         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3869         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3870         check_added_monitors!(nodes[1], 1);
3871
3872         expect_pending_htlcs_forwardable!(nodes[1]);
3873
3874         let events_5 = nodes[1].node.get_and_clear_pending_events();
3875         assert_eq!(events_5.len(), 1);
3876         match events_5[0] {
3877                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
3878                         assert_eq!(payment_hash_2, *payment_hash);
3879                         match &purpose {
3880                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3881                                         assert!(payment_preimage.is_none());
3882                                         assert_eq!(payment_secret_2, *payment_secret);
3883                                 },
3884                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3885                         }
3886                 },
3887                 _ => panic!("Unexpected event"),
3888         }
3889
3890         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3891         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3892         check_added_monitors!(nodes[0], 1);
3893
3894         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3895 }
3896
3897 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3898         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3899         // to avoid our counterparty failing the channel.
3900         let chanmon_cfgs = create_chanmon_cfgs(2);
3901         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3902         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3903         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3904
3905         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3906
3907         let our_payment_hash = if send_partial_mpp {
3908                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
3909                 // Use the utility function send_payment_along_path to send the payment with MPP data which
3910                 // indicates there are more HTLCs coming.
3911                 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.
3912                 let payment_id = PaymentId([42; 32]);
3913                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
3914                 check_added_monitors!(nodes[0], 1);
3915                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3916                 assert_eq!(events.len(), 1);
3917                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3918                 // hop should *not* yet generate any PaymentReceived event(s).
3919                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
3920                 our_payment_hash
3921         } else {
3922                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3923         };
3924
3925         let mut block = Block {
3926                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3927                 txdata: vec![],
3928         };
3929         connect_block(&nodes[0], &block);
3930         connect_block(&nodes[1], &block);
3931         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
3932         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
3933                 block.header.prev_blockhash = block.block_hash();
3934                 connect_block(&nodes[0], &block);
3935                 connect_block(&nodes[1], &block);
3936         }
3937
3938         expect_pending_htlcs_forwardable!(nodes[1]);
3939
3940         check_added_monitors!(nodes[1], 1);
3941         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3942         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3943         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3944         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3945         assert!(htlc_timeout_updates.update_fee.is_none());
3946
3947         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3948         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3949         // 100_000 msat as u64, followed by the height at which we failed back above
3950         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3951         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
3952         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
3953 }
3954
3955 #[test]
3956 fn test_htlc_timeout() {
3957         do_test_htlc_timeout(true);
3958         do_test_htlc_timeout(false);
3959 }
3960
3961 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
3962         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
3963         let chanmon_cfgs = create_chanmon_cfgs(3);
3964         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3965         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3966         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3967         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3968         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3969
3970         // Make sure all nodes are at the same starting height
3971         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
3972         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
3973         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
3974
3975         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
3976         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
3977         {
3978                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
3979         }
3980         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
3981         check_added_monitors!(nodes[1], 1);
3982
3983         // Now attempt to route a second payment, which should be placed in the holding cell
3984         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
3985         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
3986         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
3987         if forwarded_htlc {
3988                 check_added_monitors!(nodes[0], 1);
3989                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
3990                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3991                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3992                 expect_pending_htlcs_forwardable!(nodes[1]);
3993         }
3994         check_added_monitors!(nodes[1], 0);
3995
3996         connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
3997         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3998         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3999         connect_blocks(&nodes[1], 1);
4000
4001         if forwarded_htlc {
4002                 expect_pending_htlcs_forwardable!(nodes[1]);
4003                 check_added_monitors!(nodes[1], 1);
4004                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4005                 assert_eq!(fail_commit.len(), 1);
4006                 match fail_commit[0] {
4007                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4008                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4009                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4010                         },
4011                         _ => unreachable!(),
4012                 }
4013                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4014         } else {
4015                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4016         }
4017 }
4018
4019 #[test]
4020 fn test_holding_cell_htlc_add_timeouts() {
4021         do_test_holding_cell_htlc_add_timeouts(false);
4022         do_test_holding_cell_htlc_add_timeouts(true);
4023 }
4024
4025 #[test]
4026 fn test_no_txn_manager_serialize_deserialize() {
4027         let chanmon_cfgs = create_chanmon_cfgs(2);
4028         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4029         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4030         let logger: test_utils::TestLogger;
4031         let fee_estimator: test_utils::TestFeeEstimator;
4032         let persister: test_utils::TestPersister;
4033         let new_chain_monitor: test_utils::TestChainMonitor;
4034         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4035         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4036
4037         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4038
4039         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4040
4041         let nodes_0_serialized = nodes[0].node.encode();
4042         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4043         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4044
4045         logger = test_utils::TestLogger::new();
4046         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4047         persister = test_utils::TestPersister::new();
4048         let keys_manager = &chanmon_cfgs[0].keys_manager;
4049         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4050         nodes[0].chain_monitor = &new_chain_monitor;
4051         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4052         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4053                 &mut chan_0_monitor_read, keys_manager).unwrap();
4054         assert!(chan_0_monitor_read.is_empty());
4055
4056         let mut nodes_0_read = &nodes_0_serialized[..];
4057         let config = UserConfig::default();
4058         let (_, nodes_0_deserialized_tmp) = {
4059                 let mut channel_monitors = HashMap::new();
4060                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4061                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4062                         default_config: config,
4063                         keys_manager,
4064                         fee_estimator: &fee_estimator,
4065                         chain_monitor: nodes[0].chain_monitor,
4066                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4067                         logger: &logger,
4068                         channel_monitors,
4069                 }).unwrap()
4070         };
4071         nodes_0_deserialized = nodes_0_deserialized_tmp;
4072         assert!(nodes_0_read.is_empty());
4073
4074         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4075         nodes[0].node = &nodes_0_deserialized;
4076         assert_eq!(nodes[0].node.list_channels().len(), 1);
4077         check_added_monitors!(nodes[0], 1);
4078
4079         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4080         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4081         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4082         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4083
4084         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4085         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4086         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4087         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4088
4089         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4090         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4091         for node in nodes.iter() {
4092                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4093                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4094                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4095         }
4096
4097         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4098 }
4099
4100 #[test]
4101 fn mpp_failure() {
4102         let chanmon_cfgs = create_chanmon_cfgs(4);
4103         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4104         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4105         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4106
4107         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4108         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4109         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4110         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4111
4112         let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
4113         let path = route.paths[0].clone();
4114         route.paths.push(path);
4115         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
4116         route.paths[0][0].short_channel_id = chan_1_id;
4117         route.paths[0][1].short_channel_id = chan_3_id;
4118         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
4119         route.paths[1][0].short_channel_id = chan_2_id;
4120         route.paths[1][1].short_channel_id = chan_4_id;
4121         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
4122         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
4123 }
4124
4125 #[test]
4126 fn test_dup_htlc_onchain_fails_on_reload() {
4127         // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
4128         // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
4129         // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
4130         // the ChannelMonitor tells it to.
4131         //
4132         // If, due to an on-chain event, an HTLC is failed/claimed, and then we serialize the
4133         // ChannelManager, we generally expect there not to be a duplicate HTLC fail/claim (eg via a
4134         // PaymentPathFailed event appearing). However, because we may not serialize the relevant
4135         // ChannelMonitor at the same time, this isn't strictly guaranteed. In order to provide this
4136         // consistency, the ChannelManager explicitly tracks pending-onchain-resolution outbound HTLCs
4137         // and de-duplicates ChannelMonitor events.
4138         //
4139         // This tests that explicit tracking behavior.
4140         let chanmon_cfgs = create_chanmon_cfgs(2);
4141         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4142         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4143         let persister: test_utils::TestPersister;
4144         let new_chain_monitor: test_utils::TestChainMonitor;
4145         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4146         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4147
4148         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4149
4150         // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
4151         // nodes[0].
4152         let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 10000000);
4153         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
4154         check_closed_broadcast!(nodes[0], true);
4155         check_added_monitors!(nodes[0], 1);
4156         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4157
4158         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4159         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4160
4161         // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
4162         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
4163         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4164         assert_eq!(node_txn.len(), 3);
4165         assert_eq!(node_txn[0], node_txn[1]);
4166
4167         assert!(nodes[1].node.claim_funds(payment_preimage));
4168         check_added_monitors!(nodes[1], 1);
4169
4170         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4171         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4172         check_closed_broadcast!(nodes[1], true);
4173         check_added_monitors!(nodes[1], 1);
4174         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4175         let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4176
4177         header.prev_blockhash = nodes[0].best_block_hash();
4178         connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4179
4180         // Serialize out the ChannelMonitor before connecting the on-chain claim transactions. This is
4181         // fairly normal behavior as ChannelMonitor(s) are often not re-serialized when on-chain events
4182         // happen, unlike ChannelManager which tends to be re-serialized after any relevant event(s).
4183         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4184         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4185
4186         header.prev_blockhash = nodes[0].best_block_hash();
4187         let claim_block = Block { header, txdata: claim_txn};
4188         connect_block(&nodes[0], &claim_block);
4189         expect_payment_sent!(nodes[0], payment_preimage);
4190
4191         // ChannelManagers generally get re-serialized after any relevant event(s). Since we just
4192         // connected a highly-relevant block, it likely gets serialized out now.
4193         let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
4194         nodes[0].node.write(&mut chan_manager_serialized).unwrap();
4195
4196         // Now reload nodes[0]...
4197         persister = test_utils::TestPersister::new();
4198         let keys_manager = &chanmon_cfgs[0].keys_manager;
4199         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);
4200         nodes[0].chain_monitor = &new_chain_monitor;
4201         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4202         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4203                 &mut chan_0_monitor_read, keys_manager).unwrap();
4204         assert!(chan_0_monitor_read.is_empty());
4205
4206         let (_, nodes_0_deserialized_tmp) = {
4207                 let mut channel_monitors = HashMap::new();
4208                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4209                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
4210                         ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
4211                                 default_config: Default::default(),
4212                                 keys_manager,
4213                                 fee_estimator: node_cfgs[0].fee_estimator,
4214                                 chain_monitor: nodes[0].chain_monitor,
4215                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4216                                 logger: nodes[0].logger,
4217                                 channel_monitors,
4218                         }).unwrap()
4219         };
4220         nodes_0_deserialized = nodes_0_deserialized_tmp;
4221
4222         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4223         check_added_monitors!(nodes[0], 1);
4224         nodes[0].node = &nodes_0_deserialized;
4225
4226         // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
4227         // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
4228         // payment events should kick in, leaving us with no pending events here.
4229         let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
4230         nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
4231         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4232 }
4233
4234 #[test]
4235 fn test_manager_serialize_deserialize_events() {
4236         // This test makes sure the events field in ChannelManager survives de/serialization
4237         let chanmon_cfgs = create_chanmon_cfgs(2);
4238         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4239         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4240         let fee_estimator: test_utils::TestFeeEstimator;
4241         let persister: test_utils::TestPersister;
4242         let logger: test_utils::TestLogger;
4243         let new_chain_monitor: test_utils::TestChainMonitor;
4244         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4245         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4246
4247         // Start creating a channel, but stop right before broadcasting the funding transaction
4248         let channel_value = 100000;
4249         let push_msat = 10001;
4250         let a_flags = InitFeatures::known();
4251         let b_flags = InitFeatures::known();
4252         let node_a = nodes.remove(0);
4253         let node_b = nodes.remove(0);
4254         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4255         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()));
4256         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()));
4257
4258         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4259
4260         node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4261         check_added_monitors!(node_a, 0);
4262
4263         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()));
4264         {
4265                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4266                 assert_eq!(added_monitors.len(), 1);
4267                 assert_eq!(added_monitors[0].0, funding_output);
4268                 added_monitors.clear();
4269         }
4270
4271         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id()));
4272         {
4273                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4274                 assert_eq!(added_monitors.len(), 1);
4275                 assert_eq!(added_monitors[0].0, funding_output);
4276                 added_monitors.clear();
4277         }
4278         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4279
4280         nodes.push(node_a);
4281         nodes.push(node_b);
4282
4283         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4284         let nodes_0_serialized = nodes[0].node.encode();
4285         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4286         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4287
4288         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4289         logger = test_utils::TestLogger::new();
4290         persister = test_utils::TestPersister::new();
4291         let keys_manager = &chanmon_cfgs[0].keys_manager;
4292         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4293         nodes[0].chain_monitor = &new_chain_monitor;
4294         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4295         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4296                 &mut chan_0_monitor_read, keys_manager).unwrap();
4297         assert!(chan_0_monitor_read.is_empty());
4298
4299         let mut nodes_0_read = &nodes_0_serialized[..];
4300         let config = UserConfig::default();
4301         let (_, nodes_0_deserialized_tmp) = {
4302                 let mut channel_monitors = HashMap::new();
4303                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4304                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4305                         default_config: config,
4306                         keys_manager,
4307                         fee_estimator: &fee_estimator,
4308                         chain_monitor: nodes[0].chain_monitor,
4309                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4310                         logger: &logger,
4311                         channel_monitors,
4312                 }).unwrap()
4313         };
4314         nodes_0_deserialized = nodes_0_deserialized_tmp;
4315         assert!(nodes_0_read.is_empty());
4316
4317         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4318
4319         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4320         nodes[0].node = &nodes_0_deserialized;
4321
4322         // After deserializing, make sure the funding_transaction is still held by the channel manager
4323         let events_4 = nodes[0].node.get_and_clear_pending_events();
4324         assert_eq!(events_4.len(), 0);
4325         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4326         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4327
4328         // Make sure the channel is functioning as though the de/serialization never happened
4329         assert_eq!(nodes[0].node.list_channels().len(), 1);
4330         check_added_monitors!(nodes[0], 1);
4331
4332         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4333         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4334         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4335         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4336
4337         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4338         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4339         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4340         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4341
4342         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4343         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4344         for node in nodes.iter() {
4345                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4346                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4347                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4348         }
4349
4350         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4351 }
4352
4353 #[test]
4354 fn test_simple_manager_serialize_deserialize() {
4355         let chanmon_cfgs = create_chanmon_cfgs(2);
4356         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4357         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4358         let logger: test_utils::TestLogger;
4359         let fee_estimator: test_utils::TestFeeEstimator;
4360         let persister: test_utils::TestPersister;
4361         let new_chain_monitor: test_utils::TestChainMonitor;
4362         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4363         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4364         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4365
4366         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4367         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4368
4369         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4370
4371         let nodes_0_serialized = nodes[0].node.encode();
4372         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4373         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4374
4375         logger = test_utils::TestLogger::new();
4376         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4377         persister = test_utils::TestPersister::new();
4378         let keys_manager = &chanmon_cfgs[0].keys_manager;
4379         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4380         nodes[0].chain_monitor = &new_chain_monitor;
4381         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4382         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4383                 &mut chan_0_monitor_read, keys_manager).unwrap();
4384         assert!(chan_0_monitor_read.is_empty());
4385
4386         let mut nodes_0_read = &nodes_0_serialized[..];
4387         let (_, nodes_0_deserialized_tmp) = {
4388                 let mut channel_monitors = HashMap::new();
4389                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4390                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4391                         default_config: UserConfig::default(),
4392                         keys_manager,
4393                         fee_estimator: &fee_estimator,
4394                         chain_monitor: nodes[0].chain_monitor,
4395                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4396                         logger: &logger,
4397                         channel_monitors,
4398                 }).unwrap()
4399         };
4400         nodes_0_deserialized = nodes_0_deserialized_tmp;
4401         assert!(nodes_0_read.is_empty());
4402
4403         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4404         nodes[0].node = &nodes_0_deserialized;
4405         check_added_monitors!(nodes[0], 1);
4406
4407         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4408
4409         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4410         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4411 }
4412
4413 #[test]
4414 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4415         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4416         let chanmon_cfgs = create_chanmon_cfgs(4);
4417         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4418         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4419         let logger: test_utils::TestLogger;
4420         let fee_estimator: test_utils::TestFeeEstimator;
4421         let persister: test_utils::TestPersister;
4422         let new_chain_monitor: test_utils::TestChainMonitor;
4423         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4424         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4425         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4426         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4427         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4428
4429         let mut node_0_stale_monitors_serialized = Vec::new();
4430         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4431                 let mut writer = test_utils::TestVecWriter(Vec::new());
4432                 monitor.1.write(&mut writer).unwrap();
4433                 node_0_stale_monitors_serialized.push(writer.0);
4434         }
4435
4436         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4437
4438         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4439         let nodes_0_serialized = nodes[0].node.encode();
4440
4441         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4442         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4443         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4444         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4445
4446         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4447         // nodes[3])
4448         let mut node_0_monitors_serialized = Vec::new();
4449         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4450                 let mut writer = test_utils::TestVecWriter(Vec::new());
4451                 monitor.1.write(&mut writer).unwrap();
4452                 node_0_monitors_serialized.push(writer.0);
4453         }
4454
4455         logger = test_utils::TestLogger::new();
4456         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4457         persister = test_utils::TestPersister::new();
4458         let keys_manager = &chanmon_cfgs[0].keys_manager;
4459         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4460         nodes[0].chain_monitor = &new_chain_monitor;
4461
4462
4463         let mut node_0_stale_monitors = Vec::new();
4464         for serialized in node_0_stale_monitors_serialized.iter() {
4465                 let mut read = &serialized[..];
4466                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4467                 assert!(read.is_empty());
4468                 node_0_stale_monitors.push(monitor);
4469         }
4470
4471         let mut node_0_monitors = Vec::new();
4472         for serialized in node_0_monitors_serialized.iter() {
4473                 let mut read = &serialized[..];
4474                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4475                 assert!(read.is_empty());
4476                 node_0_monitors.push(monitor);
4477         }
4478
4479         let mut nodes_0_read = &nodes_0_serialized[..];
4480         if let Err(msgs::DecodeError::InvalidValue) =
4481                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4482                 default_config: UserConfig::default(),
4483                 keys_manager,
4484                 fee_estimator: &fee_estimator,
4485                 chain_monitor: nodes[0].chain_monitor,
4486                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4487                 logger: &logger,
4488                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4489         }) { } else {
4490                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4491         };
4492
4493         let mut nodes_0_read = &nodes_0_serialized[..];
4494         let (_, nodes_0_deserialized_tmp) =
4495                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4496                 default_config: UserConfig::default(),
4497                 keys_manager,
4498                 fee_estimator: &fee_estimator,
4499                 chain_monitor: nodes[0].chain_monitor,
4500                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4501                 logger: &logger,
4502                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4503         }).unwrap();
4504         nodes_0_deserialized = nodes_0_deserialized_tmp;
4505         assert!(nodes_0_read.is_empty());
4506
4507         { // Channel close should result in a commitment tx
4508                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4509                 assert_eq!(txn.len(), 1);
4510                 check_spends!(txn[0], funding_tx);
4511                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4512         }
4513
4514         for monitor in node_0_monitors.drain(..) {
4515                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4516                 check_added_monitors!(nodes[0], 1);
4517         }
4518         nodes[0].node = &nodes_0_deserialized;
4519         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4520
4521         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4522         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4523         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4524         //... and we can even still claim the payment!
4525         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4526
4527         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4528         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4529         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4530         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4531         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4532         assert_eq!(msg_events.len(), 1);
4533         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4534                 match action {
4535                         &ErrorAction::SendErrorMessage { ref msg } => {
4536                                 assert_eq!(msg.channel_id, channel_id);
4537                         },
4538                         _ => panic!("Unexpected event!"),
4539                 }
4540         }
4541 }
4542
4543 macro_rules! check_spendable_outputs {
4544         ($node: expr, $keysinterface: expr) => {
4545                 {
4546                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4547                         let mut txn = Vec::new();
4548                         let mut all_outputs = Vec::new();
4549                         let secp_ctx = Secp256k1::new();
4550                         for event in events.drain(..) {
4551                                 match event {
4552                                         Event::SpendableOutputs { mut outputs } => {
4553                                                 for outp in outputs.drain(..) {
4554                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4555                                                         all_outputs.push(outp);
4556                                                 }
4557                                         },
4558                                         _ => panic!("Unexpected event"),
4559                                 };
4560                         }
4561                         if all_outputs.len() > 1 {
4562                                 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) {
4563                                         txn.push(tx);
4564                                 }
4565                         }
4566                         txn
4567                 }
4568         }
4569 }
4570
4571 #[test]
4572 fn test_claim_sizeable_push_msat() {
4573         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4574         let chanmon_cfgs = create_chanmon_cfgs(2);
4575         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4576         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4577         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4578
4579         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4580         nodes[1].node.force_close_channel(&chan.2).unwrap();
4581         check_closed_broadcast!(nodes[1], true);
4582         check_added_monitors!(nodes[1], 1);
4583         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4584         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4585         assert_eq!(node_txn.len(), 1);
4586         check_spends!(node_txn[0], chan.3);
4587         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
4588
4589         mine_transaction(&nodes[1], &node_txn[0]);
4590         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4591
4592         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4593         assert_eq!(spend_txn.len(), 1);
4594         assert_eq!(spend_txn[0].input.len(), 1);
4595         check_spends!(spend_txn[0], node_txn[0]);
4596         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4597 }
4598
4599 #[test]
4600 fn test_claim_on_remote_sizeable_push_msat() {
4601         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4602         // to_remote output is encumbered by a P2WPKH
4603         let chanmon_cfgs = create_chanmon_cfgs(2);
4604         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4605         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4606         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4607
4608         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4609         nodes[0].node.force_close_channel(&chan.2).unwrap();
4610         check_closed_broadcast!(nodes[0], true);
4611         check_added_monitors!(nodes[0], 1);
4612         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4613
4614         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4615         assert_eq!(node_txn.len(), 1);
4616         check_spends!(node_txn[0], chan.3);
4617         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
4618
4619         mine_transaction(&nodes[1], &node_txn[0]);
4620         check_closed_broadcast!(nodes[1], true);
4621         check_added_monitors!(nodes[1], 1);
4622         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4623         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4624
4625         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4626         assert_eq!(spend_txn.len(), 1);
4627         check_spends!(spend_txn[0], node_txn[0]);
4628 }
4629
4630 #[test]
4631 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4632         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4633         // to_remote output is encumbered by a P2WPKH
4634
4635         let chanmon_cfgs = create_chanmon_cfgs(2);
4636         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4637         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4638         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4639
4640         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4641         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4642         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4643         assert_eq!(revoked_local_txn[0].input.len(), 1);
4644         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4645
4646         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4647         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4648         check_closed_broadcast!(nodes[1], true);
4649         check_added_monitors!(nodes[1], 1);
4650         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4651
4652         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4653         mine_transaction(&nodes[1], &node_txn[0]);
4654         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4655
4656         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4657         assert_eq!(spend_txn.len(), 3);
4658         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4659         check_spends!(spend_txn[1], node_txn[0]);
4660         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4661 }
4662
4663 #[test]
4664 fn test_static_spendable_outputs_preimage_tx() {
4665         let chanmon_cfgs = create_chanmon_cfgs(2);
4666         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4667         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4668         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4669
4670         // Create some initial channels
4671         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4672
4673         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4674
4675         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4676         assert_eq!(commitment_tx[0].input.len(), 1);
4677         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4678
4679         // Settle A's commitment tx on B's chain
4680         assert!(nodes[1].node.claim_funds(payment_preimage));
4681         check_added_monitors!(nodes[1], 1);
4682         mine_transaction(&nodes[1], &commitment_tx[0]);
4683         check_added_monitors!(nodes[1], 1);
4684         let events = nodes[1].node.get_and_clear_pending_msg_events();
4685         match events[0] {
4686                 MessageSendEvent::UpdateHTLCs { .. } => {},
4687                 _ => panic!("Unexpected event"),
4688         }
4689         match events[1] {
4690                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4691                 _ => panic!("Unexepected event"),
4692         }
4693
4694         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4695         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4696         assert_eq!(node_txn.len(), 3);
4697         check_spends!(node_txn[0], commitment_tx[0]);
4698         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4699         check_spends!(node_txn[1], chan_1.3);
4700         check_spends!(node_txn[2], node_txn[1]);
4701
4702         mine_transaction(&nodes[1], &node_txn[0]);
4703         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4704         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4705
4706         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4707         assert_eq!(spend_txn.len(), 1);
4708         check_spends!(spend_txn[0], node_txn[0]);
4709 }
4710
4711 #[test]
4712 fn test_static_spendable_outputs_timeout_tx() {
4713         let chanmon_cfgs = create_chanmon_cfgs(2);
4714         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4715         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4716         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4717
4718         // Create some initial channels
4719         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4720
4721         // Rebalance the network a bit by relaying one payment through all the channels ...
4722         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4723
4724         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4725
4726         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4727         assert_eq!(commitment_tx[0].input.len(), 1);
4728         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4729
4730         // Settle A's commitment tx on B' chain
4731         mine_transaction(&nodes[1], &commitment_tx[0]);
4732         check_added_monitors!(nodes[1], 1);
4733         let events = nodes[1].node.get_and_clear_pending_msg_events();
4734         match events[0] {
4735                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4736                 _ => panic!("Unexpected event"),
4737         }
4738         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4739
4740         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4741         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4742         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4743         check_spends!(node_txn[0], chan_1.3.clone());
4744         check_spends!(node_txn[1],  commitment_tx[0].clone());
4745         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4746
4747         mine_transaction(&nodes[1], &node_txn[1]);
4748         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4749         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4750         expect_payment_failed!(nodes[1], our_payment_hash, true);
4751
4752         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4753         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4754         check_spends!(spend_txn[0], commitment_tx[0]);
4755         check_spends!(spend_txn[1], node_txn[1]);
4756         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4757 }
4758
4759 #[test]
4760 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4761         let chanmon_cfgs = create_chanmon_cfgs(2);
4762         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4763         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4764         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4765
4766         // Create some initial channels
4767         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4768
4769         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4770         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4771         assert_eq!(revoked_local_txn[0].input.len(), 1);
4772         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4773
4774         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4775
4776         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4777         check_closed_broadcast!(nodes[1], true);
4778         check_added_monitors!(nodes[1], 1);
4779         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4780
4781         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4782         assert_eq!(node_txn.len(), 2);
4783         assert_eq!(node_txn[0].input.len(), 2);
4784         check_spends!(node_txn[0], revoked_local_txn[0]);
4785
4786         mine_transaction(&nodes[1], &node_txn[0]);
4787         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4788
4789         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4790         assert_eq!(spend_txn.len(), 1);
4791         check_spends!(spend_txn[0], node_txn[0]);
4792 }
4793
4794 #[test]
4795 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4796         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4797         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4798         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4799         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4800         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4801
4802         // Create some initial channels
4803         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4804
4805         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4806         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4807         assert_eq!(revoked_local_txn[0].input.len(), 1);
4808         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4809
4810         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4811
4812         // A will generate HTLC-Timeout from revoked commitment tx
4813         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4814         check_closed_broadcast!(nodes[0], true);
4815         check_added_monitors!(nodes[0], 1);
4816         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4817         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4818
4819         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4820         assert_eq!(revoked_htlc_txn.len(), 2);
4821         check_spends!(revoked_htlc_txn[0], chan_1.3);
4822         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4823         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4824         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4825         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4826
4827         // B will generate justice tx from A's revoked commitment/HTLC tx
4828         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4829         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4830         check_closed_broadcast!(nodes[1], true);
4831         check_added_monitors!(nodes[1], 1);
4832         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4833
4834         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4835         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4836         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4837         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4838         // transactions next...
4839         assert_eq!(node_txn[0].input.len(), 3);
4840         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4841
4842         assert_eq!(node_txn[1].input.len(), 2);
4843         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4844         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4845                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4846         } else {
4847                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4848                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4849         }
4850
4851         assert_eq!(node_txn[2].input.len(), 1);
4852         check_spends!(node_txn[2], chan_1.3);
4853
4854         mine_transaction(&nodes[1], &node_txn[1]);
4855         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4856
4857         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4858         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4859         assert_eq!(spend_txn.len(), 1);
4860         assert_eq!(spend_txn[0].input.len(), 1);
4861         check_spends!(spend_txn[0], node_txn[1]);
4862 }
4863
4864 #[test]
4865 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4866         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4867         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4868         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4869         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4870         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4871
4872         // Create some initial channels
4873         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4874
4875         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4876         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4877         assert_eq!(revoked_local_txn[0].input.len(), 1);
4878         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4879
4880         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4881         assert_eq!(revoked_local_txn[0].output.len(), 2);
4882
4883         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4884
4885         // B will generate HTLC-Success from revoked commitment tx
4886         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4887         check_closed_broadcast!(nodes[1], true);
4888         check_added_monitors!(nodes[1], 1);
4889         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4890         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4891
4892         assert_eq!(revoked_htlc_txn.len(), 2);
4893         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4894         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4895         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4896
4897         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4898         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4899         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4900
4901         // A will generate justice tx from B's revoked commitment/HTLC tx
4902         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4903         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4904         check_closed_broadcast!(nodes[0], true);
4905         check_added_monitors!(nodes[0], 1);
4906         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4907
4908         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4909         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4910
4911         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4912         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4913         // transactions next...
4914         assert_eq!(node_txn[0].input.len(), 2);
4915         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4916         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4917                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4918         } else {
4919                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4920                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4921         }
4922
4923         assert_eq!(node_txn[1].input.len(), 1);
4924         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4925
4926         check_spends!(node_txn[2], chan_1.3);
4927
4928         mine_transaction(&nodes[0], &node_txn[1]);
4929         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4930
4931         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4932         // didn't try to generate any new transactions.
4933
4934         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4935         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4936         assert_eq!(spend_txn.len(), 3);
4937         assert_eq!(spend_txn[0].input.len(), 1);
4938         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4939         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4940         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4941         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4942 }
4943
4944 #[test]
4945 fn test_onchain_to_onchain_claim() {
4946         // Test that in case of channel closure, we detect the state of output and claim HTLC
4947         // on downstream peer's remote commitment tx.
4948         // First, have C claim an HTLC against its own latest commitment transaction.
4949         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4950         // channel.
4951         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4952         // gets broadcast.
4953
4954         let chanmon_cfgs = create_chanmon_cfgs(3);
4955         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4956         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4957         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4958
4959         // Create some initial channels
4960         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4961         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4962
4963         // Ensure all nodes are at the same height
4964         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4965         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4966         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4967         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4968
4969         // Rebalance the network a bit by relaying one payment through all the channels ...
4970         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4971         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4972
4973         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4974         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4975         check_spends!(commitment_tx[0], chan_2.3);
4976         nodes[2].node.claim_funds(payment_preimage);
4977         check_added_monitors!(nodes[2], 1);
4978         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4979         assert!(updates.update_add_htlcs.is_empty());
4980         assert!(updates.update_fail_htlcs.is_empty());
4981         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4982         assert!(updates.update_fail_malformed_htlcs.is_empty());
4983
4984         mine_transaction(&nodes[2], &commitment_tx[0]);
4985         check_closed_broadcast!(nodes[2], true);
4986         check_added_monitors!(nodes[2], 1);
4987         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4988
4989         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4990         assert_eq!(c_txn.len(), 3);
4991         assert_eq!(c_txn[0], c_txn[2]);
4992         assert_eq!(commitment_tx[0], c_txn[1]);
4993         check_spends!(c_txn[1], chan_2.3);
4994         check_spends!(c_txn[2], c_txn[1]);
4995         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4996         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4997         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4998         assert_eq!(c_txn[0].lock_time, 0); // Success tx
4999
5000         // 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
5001         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5002         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5003         check_added_monitors!(nodes[1], 1);
5004         let events = nodes[1].node.get_and_clear_pending_events();
5005         assert_eq!(events.len(), 2);
5006         match events[0] {
5007                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5008                 _ => panic!("Unexpected event"),
5009         }
5010         match events[1] {
5011                 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
5012                         assert_eq!(fee_earned_msat, Some(1000));
5013                         assert_eq!(claim_from_onchain_tx, true);
5014                 },
5015                 _ => panic!("Unexpected event"),
5016         }
5017         {
5018                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5019                 // ChannelMonitor: claim tx
5020                 assert_eq!(b_txn.len(), 1);
5021                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5022                 b_txn.clear();
5023         }
5024         check_added_monitors!(nodes[1], 1);
5025         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5026         assert_eq!(msg_events.len(), 3);
5027         match msg_events[0] {
5028                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5029                 _ => panic!("Unexpected event"),
5030         }
5031         match msg_events[1] {
5032                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5033                 _ => panic!("Unexpected event"),
5034         }
5035         match msg_events[2] {
5036                 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, .. } } => {
5037                         assert!(update_add_htlcs.is_empty());
5038                         assert!(update_fail_htlcs.is_empty());
5039                         assert_eq!(update_fulfill_htlcs.len(), 1);
5040                         assert!(update_fail_malformed_htlcs.is_empty());
5041                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5042                 },
5043                 _ => panic!("Unexpected event"),
5044         };
5045         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5046         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5047         mine_transaction(&nodes[1], &commitment_tx[0]);
5048         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5049         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5050         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5051         assert_eq!(b_txn.len(), 3);
5052         check_spends!(b_txn[1], chan_1.3);
5053         check_spends!(b_txn[2], b_txn[1]);
5054         check_spends!(b_txn[0], commitment_tx[0]);
5055         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5056         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5057         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5058
5059         check_closed_broadcast!(nodes[1], true);
5060         check_added_monitors!(nodes[1], 1);
5061 }
5062
5063 #[test]
5064 fn test_duplicate_payment_hash_one_failure_one_success() {
5065         // Topology : A --> B --> C --> D
5066         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5067         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5068         // we forward one of the payments onwards to D.
5069         let chanmon_cfgs = create_chanmon_cfgs(4);
5070         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5071         // When this test was written, the default base fee floated based on the HTLC count.
5072         // It is now fixed, so we simply set the fee to the expected value here.
5073         let mut config = test_default_channel_config();
5074         config.channel_options.forwarding_fee_base_msat = 196;
5075         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5076                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5077         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5078
5079         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5080         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5081         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5082
5083         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5084         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5085         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5086         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5087         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5088
5089         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5090
5091         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, 0).unwrap();
5092         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5093         // script push size limit so that the below script length checks match
5094         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5095         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], vec![], 900000, TEST_FINAL_CLTV - 40);
5096         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5097
5098         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5099         assert_eq!(commitment_txn[0].input.len(), 1);
5100         check_spends!(commitment_txn[0], chan_2.3);
5101
5102         mine_transaction(&nodes[1], &commitment_txn[0]);
5103         check_closed_broadcast!(nodes[1], true);
5104         check_added_monitors!(nodes[1], 1);
5105         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5106         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5107
5108         let htlc_timeout_tx;
5109         { // Extract one of the two HTLC-Timeout transaction
5110                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5111                 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5112                 assert_eq!(node_txn.len(), 4);
5113                 check_spends!(node_txn[0], chan_2.3);
5114
5115                 check_spends!(node_txn[1], commitment_txn[0]);
5116                 assert_eq!(node_txn[1].input.len(), 1);
5117                 check_spends!(node_txn[2], commitment_txn[0]);
5118                 assert_eq!(node_txn[2].input.len(), 1);
5119                 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5120                 check_spends!(node_txn[3], commitment_txn[0]);
5121                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5122
5123                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5124                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5125                 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5126                 htlc_timeout_tx = node_txn[1].clone();
5127         }
5128
5129         nodes[2].node.claim_funds(our_payment_preimage);
5130         mine_transaction(&nodes[2], &commitment_txn[0]);
5131         check_added_monitors!(nodes[2], 2);
5132         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5133         let events = nodes[2].node.get_and_clear_pending_msg_events();
5134         match events[0] {
5135                 MessageSendEvent::UpdateHTLCs { .. } => {},
5136                 _ => panic!("Unexpected event"),
5137         }
5138         match events[1] {
5139                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5140                 _ => panic!("Unexepected event"),
5141         }
5142         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5143         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)
5144         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5145         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5146         assert_eq!(htlc_success_txn[0].input.len(), 1);
5147         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5148         assert_eq!(htlc_success_txn[1].input.len(), 1);
5149         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5150         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5151         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5152         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5153         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5154         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5155
5156         mine_transaction(&nodes[1], &htlc_timeout_tx);
5157         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5158         expect_pending_htlcs_forwardable!(nodes[1]);
5159         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5160         assert!(htlc_updates.update_add_htlcs.is_empty());
5161         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5162         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5163         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5164         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5165         check_added_monitors!(nodes[1], 1);
5166
5167         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5168         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5169         {
5170                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5171         }
5172         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5173
5174         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5175         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5176         // and nodes[2] fee) is rounded down and then claimed in full.
5177         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5178         expect_payment_forwarded!(nodes[1], Some(196*2), true);
5179         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5180         assert!(updates.update_add_htlcs.is_empty());
5181         assert!(updates.update_fail_htlcs.is_empty());
5182         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5183         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5184         assert!(updates.update_fail_malformed_htlcs.is_empty());
5185         check_added_monitors!(nodes[1], 1);
5186
5187         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5188         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5189
5190         let events = nodes[0].node.get_and_clear_pending_events();
5191         match events[0] {
5192                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
5193                         assert_eq!(*payment_preimage, our_payment_preimage);
5194                         assert_eq!(*payment_hash, duplicate_payment_hash);
5195                 }
5196                 _ => panic!("Unexpected event"),
5197         }
5198 }
5199
5200 #[test]
5201 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5202         let chanmon_cfgs = create_chanmon_cfgs(2);
5203         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5204         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5205         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5206
5207         // Create some initial channels
5208         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5209
5210         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5211         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5212         assert_eq!(local_txn.len(), 1);
5213         assert_eq!(local_txn[0].input.len(), 1);
5214         check_spends!(local_txn[0], chan_1.3);
5215
5216         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5217         nodes[1].node.claim_funds(payment_preimage);
5218         check_added_monitors!(nodes[1], 1);
5219         mine_transaction(&nodes[1], &local_txn[0]);
5220         check_added_monitors!(nodes[1], 1);
5221         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5222         let events = nodes[1].node.get_and_clear_pending_msg_events();
5223         match events[0] {
5224                 MessageSendEvent::UpdateHTLCs { .. } => {},
5225                 _ => panic!("Unexpected event"),
5226         }
5227         match events[1] {
5228                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5229                 _ => panic!("Unexepected event"),
5230         }
5231         let node_tx = {
5232                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5233                 assert_eq!(node_txn.len(), 3);
5234                 assert_eq!(node_txn[0], node_txn[2]);
5235                 assert_eq!(node_txn[1], local_txn[0]);
5236                 assert_eq!(node_txn[0].input.len(), 1);
5237                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5238                 check_spends!(node_txn[0], local_txn[0]);
5239                 node_txn[0].clone()
5240         };
5241
5242         mine_transaction(&nodes[1], &node_tx);
5243         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5244
5245         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5246         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5247         assert_eq!(spend_txn.len(), 1);
5248         assert_eq!(spend_txn[0].input.len(), 1);
5249         check_spends!(spend_txn[0], node_tx);
5250         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5251 }
5252
5253 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5254         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5255         // unrevoked commitment transaction.
5256         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5257         // a remote RAA before they could be failed backwards (and combinations thereof).
5258         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5259         // use the same payment hashes.
5260         // Thus, we use a six-node network:
5261         //
5262         // A \         / E
5263         //    - C - D -
5264         // B /         \ F
5265         // And test where C fails back to A/B when D announces its latest commitment transaction
5266         let chanmon_cfgs = create_chanmon_cfgs(6);
5267         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5268         // When this test was written, the default base fee floated based on the HTLC count.
5269         // It is now fixed, so we simply set the fee to the expected value here.
5270         let mut config = test_default_channel_config();
5271         config.channel_options.forwarding_fee_base_msat = 196;
5272         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5273                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5274         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5275
5276         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5277         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5278         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5279         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5280         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5281
5282         // Rebalance and check output sanity...
5283         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5284         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5285         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5286
5287         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5288         // 0th HTLC:
5289         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
5290         // 1st HTLC:
5291         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
5292         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5293         // 2nd HTLC:
5294         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
5295         // 3rd HTLC:
5296         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
5297         // 4th HTLC:
5298         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5299         // 5th HTLC:
5300         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5301         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5302         // 6th HTLC:
5303         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());
5304         // 7th HTLC:
5305         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());
5306
5307         // 8th HTLC:
5308         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5309         // 9th HTLC:
5310         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5311         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
5312
5313         // 10th HTLC:
5314         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
5315         // 11th HTLC:
5316         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5317         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());
5318
5319         // Double-check that six of the new HTLC were added
5320         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5321         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5322         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5323         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5324
5325         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5326         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5327         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5328         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5329         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5330         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5331         check_added_monitors!(nodes[4], 0);
5332         expect_pending_htlcs_forwardable!(nodes[4]);
5333         check_added_monitors!(nodes[4], 1);
5334
5335         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5336         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5337         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5338         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5339         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5340         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5341
5342         // Fail 3rd below-dust and 7th above-dust HTLCs
5343         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5344         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5345         check_added_monitors!(nodes[5], 0);
5346         expect_pending_htlcs_forwardable!(nodes[5]);
5347         check_added_monitors!(nodes[5], 1);
5348
5349         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5350         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5351         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5352         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5353
5354         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5355
5356         expect_pending_htlcs_forwardable!(nodes[3]);
5357         check_added_monitors!(nodes[3], 1);
5358         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5359         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5360         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5361         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5362         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5363         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5364         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5365         if deliver_last_raa {
5366                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5367         } else {
5368                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5369         }
5370
5371         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5372         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5373         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5374         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5375         //
5376         // We now broadcast the latest commitment transaction, which *should* result in failures for
5377         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5378         // the non-broadcast above-dust HTLCs.
5379         //
5380         // Alternatively, we may broadcast the previous commitment transaction, which should only
5381         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5382         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5383
5384         if announce_latest {
5385                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5386         } else {
5387                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5388         }
5389         let events = nodes[2].node.get_and_clear_pending_events();
5390         let close_event = if deliver_last_raa {
5391                 assert_eq!(events.len(), 2);
5392                 events[1].clone()
5393         } else {
5394                 assert_eq!(events.len(), 1);
5395                 events[0].clone()
5396         };
5397         match close_event {
5398                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5399                 _ => panic!("Unexpected event"),
5400         }
5401
5402         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5403         check_closed_broadcast!(nodes[2], true);
5404         if deliver_last_raa {
5405                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5406         } else {
5407                 expect_pending_htlcs_forwardable!(nodes[2]);
5408         }
5409         check_added_monitors!(nodes[2], 3);
5410
5411         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5412         assert_eq!(cs_msgs.len(), 2);
5413         let mut a_done = false;
5414         for msg in cs_msgs {
5415                 match msg {
5416                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5417                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5418                                 // should be failed-backwards here.
5419                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5420                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5421                                         for htlc in &updates.update_fail_htlcs {
5422                                                 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 });
5423                                         }
5424                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5425                                         assert!(!a_done);
5426                                         a_done = true;
5427                                         &nodes[0]
5428                                 } else {
5429                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5430                                         for htlc in &updates.update_fail_htlcs {
5431                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5432                                         }
5433                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5434                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5435                                         &nodes[1]
5436                                 };
5437                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5438                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5439                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5440                                 if announce_latest {
5441                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5442                                         if *node_id == nodes[0].node.get_our_node_id() {
5443                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5444                                         }
5445                                 }
5446                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5447                         },
5448                         _ => panic!("Unexpected event"),
5449                 }
5450         }
5451
5452         let as_events = nodes[0].node.get_and_clear_pending_events();
5453         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5454         let mut as_failds = HashSet::new();
5455         let mut as_updates = 0;
5456         for event in as_events.iter() {
5457                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5458                         assert!(as_failds.insert(*payment_hash));
5459                         if *payment_hash != payment_hash_2 {
5460                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5461                         } else {
5462                                 assert!(!rejected_by_dest);
5463                         }
5464                         if network_update.is_some() {
5465                                 as_updates += 1;
5466                         }
5467                 } else { panic!("Unexpected event"); }
5468         }
5469         assert!(as_failds.contains(&payment_hash_1));
5470         assert!(as_failds.contains(&payment_hash_2));
5471         if announce_latest {
5472                 assert!(as_failds.contains(&payment_hash_3));
5473                 assert!(as_failds.contains(&payment_hash_5));
5474         }
5475         assert!(as_failds.contains(&payment_hash_6));
5476
5477         let bs_events = nodes[1].node.get_and_clear_pending_events();
5478         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5479         let mut bs_failds = HashSet::new();
5480         let mut bs_updates = 0;
5481         for event in bs_events.iter() {
5482                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5483                         assert!(bs_failds.insert(*payment_hash));
5484                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5485                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5486                         } else {
5487                                 assert!(!rejected_by_dest);
5488                         }
5489                         if network_update.is_some() {
5490                                 bs_updates += 1;
5491                         }
5492                 } else { panic!("Unexpected event"); }
5493         }
5494         assert!(bs_failds.contains(&payment_hash_1));
5495         assert!(bs_failds.contains(&payment_hash_2));
5496         if announce_latest {
5497                 assert!(bs_failds.contains(&payment_hash_4));
5498         }
5499         assert!(bs_failds.contains(&payment_hash_5));
5500
5501         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5502         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5503         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5504         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5505         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5506         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5507 }
5508
5509 #[test]
5510 fn test_fail_backwards_latest_remote_announce_a() {
5511         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5512 }
5513
5514 #[test]
5515 fn test_fail_backwards_latest_remote_announce_b() {
5516         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5517 }
5518
5519 #[test]
5520 fn test_fail_backwards_previous_remote_announce() {
5521         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5522         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5523         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5524 }
5525
5526 #[test]
5527 fn test_dynamic_spendable_outputs_local_htlc_timeout_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         // Create some initial channels
5534         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5535
5536         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5537         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5538         assert_eq!(local_txn[0].input.len(), 1);
5539         check_spends!(local_txn[0], chan_1.3);
5540
5541         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5542         mine_transaction(&nodes[0], &local_txn[0]);
5543         check_closed_broadcast!(nodes[0], true);
5544         check_added_monitors!(nodes[0], 1);
5545         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5546         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5547
5548         let htlc_timeout = {
5549                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5550                 assert_eq!(node_txn.len(), 2);
5551                 check_spends!(node_txn[0], chan_1.3);
5552                 assert_eq!(node_txn[1].input.len(), 1);
5553                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5554                 check_spends!(node_txn[1], local_txn[0]);
5555                 node_txn[1].clone()
5556         };
5557
5558         mine_transaction(&nodes[0], &htlc_timeout);
5559         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5560         expect_payment_failed!(nodes[0], our_payment_hash, true);
5561
5562         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5563         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5564         assert_eq!(spend_txn.len(), 3);
5565         check_spends!(spend_txn[0], local_txn[0]);
5566         assert_eq!(spend_txn[1].input.len(), 1);
5567         check_spends!(spend_txn[1], htlc_timeout);
5568         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5569         assert_eq!(spend_txn[2].input.len(), 2);
5570         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5571         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5572                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5573 }
5574
5575 #[test]
5576 fn test_key_derivation_params() {
5577         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5578         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5579         // let us re-derive the channel key set to then derive a delayed_payment_key.
5580
5581         let chanmon_cfgs = create_chanmon_cfgs(3);
5582
5583         // We manually create the node configuration to backup the seed.
5584         let seed = [42; 32];
5585         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5586         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);
5587         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, node_seed: seed, features: InitFeatures::known() };
5588         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5589         node_cfgs.remove(0);
5590         node_cfgs.insert(0, node);
5591
5592         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5593         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5594
5595         // Create some initial channels
5596         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5597         // for node 0
5598         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5599         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5600         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5601
5602         // Ensure all nodes are at the same height
5603         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5604         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5605         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5606         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5607
5608         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5609         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5610         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5611         assert_eq!(local_txn_1[0].input.len(), 1);
5612         check_spends!(local_txn_1[0], chan_1.3);
5613
5614         // We check funding pubkey are unique
5615         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]));
5616         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]));
5617         if from_0_funding_key_0 == from_1_funding_key_0
5618             || from_0_funding_key_0 == from_1_funding_key_1
5619             || from_0_funding_key_1 == from_1_funding_key_0
5620             || from_0_funding_key_1 == from_1_funding_key_1 {
5621                 panic!("Funding pubkeys aren't unique");
5622         }
5623
5624         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5625         mine_transaction(&nodes[0], &local_txn_1[0]);
5626         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
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         let htlc_timeout = {
5632                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5633                 assert_eq!(node_txn[1].input.len(), 1);
5634                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5635                 check_spends!(node_txn[1], local_txn_1[0]);
5636                 node_txn[1].clone()
5637         };
5638
5639         mine_transaction(&nodes[0], &htlc_timeout);
5640         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5641         expect_payment_failed!(nodes[0], our_payment_hash, true);
5642
5643         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5644         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5645         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5646         assert_eq!(spend_txn.len(), 3);
5647         check_spends!(spend_txn[0], local_txn_1[0]);
5648         assert_eq!(spend_txn[1].input.len(), 1);
5649         check_spends!(spend_txn[1], htlc_timeout);
5650         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5651         assert_eq!(spend_txn[2].input.len(), 2);
5652         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5653         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5654                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5655 }
5656
5657 #[test]
5658 fn test_static_output_closing_tx() {
5659         let chanmon_cfgs = create_chanmon_cfgs(2);
5660         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5661         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5662         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5663
5664         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5665
5666         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5667         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5668
5669         mine_transaction(&nodes[0], &closing_tx);
5670         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5671         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5672
5673         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5674         assert_eq!(spend_txn.len(), 1);
5675         check_spends!(spend_txn[0], closing_tx);
5676
5677         mine_transaction(&nodes[1], &closing_tx);
5678         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5679         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5680
5681         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5682         assert_eq!(spend_txn.len(), 1);
5683         check_spends!(spend_txn[0], closing_tx);
5684 }
5685
5686 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5687         let chanmon_cfgs = create_chanmon_cfgs(2);
5688         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5689         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5690         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5691         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5692
5693         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5694
5695         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5696         // present in B's local commitment transaction, but none of A's commitment transactions.
5697         assert!(nodes[1].node.claim_funds(our_payment_preimage));
5698         check_added_monitors!(nodes[1], 1);
5699
5700         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5701         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5702         let events = nodes[0].node.get_and_clear_pending_events();
5703         assert_eq!(events.len(), 1);
5704         match events[0] {
5705                 Event::PaymentSent { payment_preimage, payment_hash } => {
5706                         assert_eq!(payment_preimage, our_payment_preimage);
5707                         assert_eq!(payment_hash, our_payment_hash);
5708                 },
5709                 _ => panic!("Unexpected event"),
5710         }
5711
5712         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5713         check_added_monitors!(nodes[0], 1);
5714         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5715         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5716         check_added_monitors!(nodes[1], 1);
5717
5718         let starting_block = nodes[1].best_block_info();
5719         let mut block = Block {
5720                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5721                 txdata: vec![],
5722         };
5723         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5724                 connect_block(&nodes[1], &block);
5725                 block.header.prev_blockhash = block.block_hash();
5726         }
5727         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5728         check_closed_broadcast!(nodes[1], true);
5729         check_added_monitors!(nodes[1], 1);
5730         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5731 }
5732
5733 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5734         let chanmon_cfgs = create_chanmon_cfgs(2);
5735         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5736         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5737         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5738         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5739
5740         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5741         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5742         check_added_monitors!(nodes[0], 1);
5743
5744         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5745
5746         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5747         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5748         // to "time out" the HTLC.
5749
5750         let starting_block = nodes[1].best_block_info();
5751         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5752
5753         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5754                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5755                 header.prev_blockhash = header.block_hash();
5756         }
5757         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5758         check_closed_broadcast!(nodes[0], true);
5759         check_added_monitors!(nodes[0], 1);
5760         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5761 }
5762
5763 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5764         let chanmon_cfgs = create_chanmon_cfgs(3);
5765         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5766         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5767         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5768         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5769
5770         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5771         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5772         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5773         // actually revoked.
5774         let htlc_value = if use_dust { 50000 } else { 3000000 };
5775         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5776         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5777         expect_pending_htlcs_forwardable!(nodes[1]);
5778         check_added_monitors!(nodes[1], 1);
5779
5780         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5781         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5782         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5783         check_added_monitors!(nodes[0], 1);
5784         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5785         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5786         check_added_monitors!(nodes[1], 1);
5787         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5788         check_added_monitors!(nodes[1], 1);
5789         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5790
5791         if check_revoke_no_close {
5792                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5793                 check_added_monitors!(nodes[0], 1);
5794         }
5795
5796         let starting_block = nodes[1].best_block_info();
5797         let mut block = Block {
5798                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5799                 txdata: vec![],
5800         };
5801         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5802                 connect_block(&nodes[0], &block);
5803                 block.header.prev_blockhash = block.block_hash();
5804         }
5805         if !check_revoke_no_close {
5806                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5807                 check_closed_broadcast!(nodes[0], true);
5808                 check_added_monitors!(nodes[0], 1);
5809                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5810         } else {
5811                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5812         }
5813 }
5814
5815 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5816 // There are only a few cases to test here:
5817 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5818 //    broadcastable commitment transactions result in channel closure,
5819 //  * its included in an unrevoked-but-previous remote commitment transaction,
5820 //  * its included in the latest remote or local commitment transactions.
5821 // We test each of the three possible commitment transactions individually and use both dust and
5822 // non-dust HTLCs.
5823 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5824 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5825 // tested for at least one of the cases in other tests.
5826 #[test]
5827 fn htlc_claim_single_commitment_only_a() {
5828         do_htlc_claim_local_commitment_only(true);
5829         do_htlc_claim_local_commitment_only(false);
5830
5831         do_htlc_claim_current_remote_commitment_only(true);
5832         do_htlc_claim_current_remote_commitment_only(false);
5833 }
5834
5835 #[test]
5836 fn htlc_claim_single_commitment_only_b() {
5837         do_htlc_claim_previous_remote_commitment_only(true, false);
5838         do_htlc_claim_previous_remote_commitment_only(false, false);
5839         do_htlc_claim_previous_remote_commitment_only(true, true);
5840         do_htlc_claim_previous_remote_commitment_only(false, true);
5841 }
5842
5843 #[test]
5844 #[should_panic]
5845 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5846         let chanmon_cfgs = create_chanmon_cfgs(2);
5847         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5848         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5849         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5850         //Force duplicate channel ids
5851         for node in nodes.iter() {
5852                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5853         }
5854
5855         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5856         let channel_value_satoshis=10000;
5857         let push_msat=10001;
5858         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5859         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5860         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5861
5862         //Create a second channel with a channel_id collision
5863         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5864 }
5865
5866 #[test]
5867 fn bolt2_open_channel_sending_node_checks_part2() {
5868         let chanmon_cfgs = create_chanmon_cfgs(2);
5869         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5870         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5871         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5872
5873         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5874         let channel_value_satoshis=2^24;
5875         let push_msat=10001;
5876         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5877
5878         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5879         let channel_value_satoshis=10000;
5880         // Test when push_msat is equal to 1000 * funding_satoshis.
5881         let push_msat=1000*channel_value_satoshis+1;
5882         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5883
5884         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5885         let channel_value_satoshis=10000;
5886         let push_msat=10001;
5887         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
5888         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5889         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5890
5891         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5892         // 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
5893         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5894
5895         // 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.
5896         assert!(BREAKDOWN_TIMEOUT>0);
5897         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5898
5899         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5900         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5901         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5902
5903         // 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.
5904         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5905         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5906         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5907         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5908         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5909 }
5910
5911 #[test]
5912 fn bolt2_open_channel_sane_dust_limit() {
5913         let chanmon_cfgs = create_chanmon_cfgs(2);
5914         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5915         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5916         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5917
5918         let channel_value_satoshis=1000000;
5919         let push_msat=10001;
5920         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5921         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5922         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5923         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5924
5925         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5926         let events = nodes[1].node.get_and_clear_pending_msg_events();
5927         let err_msg = match events[0] {
5928                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5929                         msg.clone()
5930                 },
5931                 _ => panic!("Unexpected event"),
5932         };
5933         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5934 }
5935
5936 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5937 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5938 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5939 // is no longer affordable once it's freed.
5940 #[test]
5941 fn test_fail_holding_cell_htlc_upon_free() {
5942         let chanmon_cfgs = create_chanmon_cfgs(2);
5943         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5944         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5945         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5946         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5947
5948         // First nodes[0] generates an update_fee, setting the channel's
5949         // pending_update_fee.
5950         {
5951                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5952                 *feerate_lock += 20;
5953         }
5954         nodes[0].node.timer_tick_occurred();
5955         check_added_monitors!(nodes[0], 1);
5956
5957         let events = nodes[0].node.get_and_clear_pending_msg_events();
5958         assert_eq!(events.len(), 1);
5959         let (update_msg, commitment_signed) = match events[0] {
5960                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5961                         (update_fee.as_ref(), commitment_signed)
5962                 },
5963                 _ => panic!("Unexpected event"),
5964         };
5965
5966         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5967
5968         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5969         let channel_reserve = chan_stat.channel_reserve_msat;
5970         let feerate = get_feerate!(nodes[0], chan.2);
5971
5972         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5973         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5974         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5975
5976         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5977         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
5978         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5979         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5980
5981         // Flush the pending fee update.
5982         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5983         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5984         check_added_monitors!(nodes[1], 1);
5985         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5986         check_added_monitors!(nodes[0], 1);
5987
5988         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5989         // HTLC, but now that the fee has been raised the payment will now fail, causing
5990         // us to surface its failure to the user.
5991         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5992         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5993         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);
5994         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 {}",
5995                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5996         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5997
5998         // Check that the payment failed to be sent out.
5999         let events = nodes[0].node.get_and_clear_pending_events();
6000         assert_eq!(events.len(), 1);
6001         match &events[0] {
6002                 &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, path: _, ref short_channel_id, ref error_code, ref error_data } => {
6003                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6004                         assert_eq!(*rejected_by_dest, false);
6005                         assert_eq!(*all_paths_failed, true);
6006                         assert_eq!(*network_update, None);
6007                         assert_eq!(*short_channel_id, None);
6008                         assert_eq!(*error_code, None);
6009                         assert_eq!(*error_data, None);
6010                 },
6011                 _ => panic!("Unexpected event"),
6012         }
6013 }
6014
6015 // Test that if multiple HTLCs are released from the holding cell and one is
6016 // valid but the other is no longer valid upon release, the valid HTLC can be
6017 // successfully completed while the other one fails as expected.
6018 #[test]
6019 fn test_free_and_fail_holding_cell_htlcs() {
6020         let chanmon_cfgs = create_chanmon_cfgs(2);
6021         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6022         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6023         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6024         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6025
6026         // First nodes[0] generates an update_fee, setting the channel's
6027         // pending_update_fee.
6028         {
6029                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6030                 *feerate_lock += 200;
6031         }
6032         nodes[0].node.timer_tick_occurred();
6033         check_added_monitors!(nodes[0], 1);
6034
6035         let events = nodes[0].node.get_and_clear_pending_msg_events();
6036         assert_eq!(events.len(), 1);
6037         let (update_msg, commitment_signed) = match events[0] {
6038                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6039                         (update_fee.as_ref(), commitment_signed)
6040                 },
6041                 _ => panic!("Unexpected event"),
6042         };
6043
6044         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6045
6046         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6047         let channel_reserve = chan_stat.channel_reserve_msat;
6048         let feerate = get_feerate!(nodes[0], chan.2);
6049
6050         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6051         let amt_1 = 20000;
6052         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6053         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6054         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6055
6056         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6057         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6058         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6059         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6060         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6061         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6062         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6063
6064         // Flush the pending fee update.
6065         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6066         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6067         check_added_monitors!(nodes[1], 1);
6068         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6069         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6070         check_added_monitors!(nodes[0], 2);
6071
6072         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6073         // but now that the fee has been raised the second payment will now fail, causing us
6074         // to surface its failure to the user. The first payment should succeed.
6075         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6076         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6077         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);
6078         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 {}",
6079                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6080         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6081
6082         // Check that the second payment failed to be sent out.
6083         let events = nodes[0].node.get_and_clear_pending_events();
6084         assert_eq!(events.len(), 1);
6085         match &events[0] {
6086                 &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, path: _, ref short_channel_id, ref error_code, ref error_data } => {
6087                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6088                         assert_eq!(*rejected_by_dest, false);
6089                         assert_eq!(*all_paths_failed, true);
6090                         assert_eq!(*network_update, None);
6091                         assert_eq!(*short_channel_id, None);
6092                         assert_eq!(*error_code, None);
6093                         assert_eq!(*error_data, None);
6094                 },
6095                 _ => panic!("Unexpected event"),
6096         }
6097
6098         // Complete the first payment and the RAA from the fee update.
6099         let (payment_event, send_raa_event) = {
6100                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6101                 assert_eq!(msgs.len(), 2);
6102                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6103         };
6104         let raa = match send_raa_event {
6105                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6106                 _ => panic!("Unexpected event"),
6107         };
6108         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6109         check_added_monitors!(nodes[1], 1);
6110         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6111         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6112         let events = nodes[1].node.get_and_clear_pending_events();
6113         assert_eq!(events.len(), 1);
6114         match events[0] {
6115                 Event::PendingHTLCsForwardable { .. } => {},
6116                 _ => panic!("Unexpected event"),
6117         }
6118         nodes[1].node.process_pending_htlc_forwards();
6119         let events = nodes[1].node.get_and_clear_pending_events();
6120         assert_eq!(events.len(), 1);
6121         match events[0] {
6122                 Event::PaymentReceived { .. } => {},
6123                 _ => panic!("Unexpected event"),
6124         }
6125         nodes[1].node.claim_funds(payment_preimage_1);
6126         check_added_monitors!(nodes[1], 1);
6127         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6128         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6129         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6130         let events = nodes[0].node.get_and_clear_pending_events();
6131         assert_eq!(events.len(), 1);
6132         match events[0] {
6133                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
6134                         assert_eq!(*payment_preimage, payment_preimage_1);
6135                         assert_eq!(*payment_hash, payment_hash_1);
6136                 }
6137                 _ => panic!("Unexpected event"),
6138         }
6139 }
6140
6141 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6142 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6143 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6144 // once it's freed.
6145 #[test]
6146 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6147         let chanmon_cfgs = create_chanmon_cfgs(3);
6148         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6149         // When this test was written, the default base fee floated based on the HTLC count.
6150         // It is now fixed, so we simply set the fee to the expected value here.
6151         let mut config = test_default_channel_config();
6152         config.channel_options.forwarding_fee_base_msat = 196;
6153         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6154         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6155         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6156         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6157
6158         // First nodes[1] generates an update_fee, setting the channel's
6159         // pending_update_fee.
6160         {
6161                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6162                 *feerate_lock += 20;
6163         }
6164         nodes[1].node.timer_tick_occurred();
6165         check_added_monitors!(nodes[1], 1);
6166
6167         let events = nodes[1].node.get_and_clear_pending_msg_events();
6168         assert_eq!(events.len(), 1);
6169         let (update_msg, commitment_signed) = match events[0] {
6170                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6171                         (update_fee.as_ref(), commitment_signed)
6172                 },
6173                 _ => panic!("Unexpected event"),
6174         };
6175
6176         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6177
6178         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6179         let channel_reserve = chan_stat.channel_reserve_msat;
6180         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6181
6182         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6183         let feemsat = 239;
6184         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6185         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6186         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6187         let payment_event = {
6188                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6189                 check_added_monitors!(nodes[0], 1);
6190
6191                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6192                 assert_eq!(events.len(), 1);
6193
6194                 SendEvent::from_event(events.remove(0))
6195         };
6196         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6197         check_added_monitors!(nodes[1], 0);
6198         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6199         expect_pending_htlcs_forwardable!(nodes[1]);
6200
6201         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6202         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6203
6204         // Flush the pending fee update.
6205         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6206         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6207         check_added_monitors!(nodes[2], 1);
6208         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6209         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6210         check_added_monitors!(nodes[1], 2);
6211
6212         // A final RAA message is generated to finalize the fee update.
6213         let events = nodes[1].node.get_and_clear_pending_msg_events();
6214         assert_eq!(events.len(), 1);
6215
6216         let raa_msg = match &events[0] {
6217                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6218                         msg.clone()
6219                 },
6220                 _ => panic!("Unexpected event"),
6221         };
6222
6223         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6224         check_added_monitors!(nodes[2], 1);
6225         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6226
6227         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6228         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6229         assert_eq!(process_htlc_forwards_event.len(), 1);
6230         match &process_htlc_forwards_event[0] {
6231                 &Event::PendingHTLCsForwardable { .. } => {},
6232                 _ => panic!("Unexpected event"),
6233         }
6234
6235         // In response, we call ChannelManager's process_pending_htlc_forwards
6236         nodes[1].node.process_pending_htlc_forwards();
6237         check_added_monitors!(nodes[1], 1);
6238
6239         // This causes the HTLC to be failed backwards.
6240         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6241         assert_eq!(fail_event.len(), 1);
6242         let (fail_msg, commitment_signed) = match &fail_event[0] {
6243                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6244                         assert_eq!(updates.update_add_htlcs.len(), 0);
6245                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6246                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6247                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6248                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6249                 },
6250                 _ => panic!("Unexpected event"),
6251         };
6252
6253         // Pass the failure messages back to nodes[0].
6254         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6255         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6256
6257         // Complete the HTLC failure+removal process.
6258         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6259         check_added_monitors!(nodes[0], 1);
6260         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6261         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6262         check_added_monitors!(nodes[1], 2);
6263         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6264         assert_eq!(final_raa_event.len(), 1);
6265         let raa = match &final_raa_event[0] {
6266                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6267                 _ => panic!("Unexpected event"),
6268         };
6269         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6270         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6271         check_added_monitors!(nodes[0], 1);
6272 }
6273
6274 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6275 // 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.
6276 //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.
6277
6278 #[test]
6279 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6280         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6281         let chanmon_cfgs = create_chanmon_cfgs(2);
6282         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6283         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6284         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6285         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6286
6287         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6288         route.paths[0][0].fee_msat = 100;
6289
6290         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6291                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6292         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6293         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6294 }
6295
6296 #[test]
6297 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6298         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6299         let chanmon_cfgs = create_chanmon_cfgs(2);
6300         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6301         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6302         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6303         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6304
6305         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6306         route.paths[0][0].fee_msat = 0;
6307         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6308                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6309
6310         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6311         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6312 }
6313
6314 #[test]
6315 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6316         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6317         let chanmon_cfgs = create_chanmon_cfgs(2);
6318         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6319         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6320         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6321         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6322
6323         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6324         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6325         check_added_monitors!(nodes[0], 1);
6326         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6327         updates.update_add_htlcs[0].amount_msat = 0;
6328
6329         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6330         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6331         check_closed_broadcast!(nodes[1], true).unwrap();
6332         check_added_monitors!(nodes[1], 1);
6333         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6334 }
6335
6336 #[test]
6337 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6338         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6339         //It is enforced when constructing a route.
6340         let chanmon_cfgs = create_chanmon_cfgs(2);
6341         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6342         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6343         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6344         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6345
6346         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], vec![], 100000000, 500000001);
6347         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6348                 assert_eq!(err, &"Channel CLTV overflowed?"));
6349 }
6350
6351 #[test]
6352 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6353         //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.
6354         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6355         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6356         let chanmon_cfgs = create_chanmon_cfgs(2);
6357         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6358         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6359         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6360         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6361         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6362
6363         for i in 0..max_accepted_htlcs {
6364                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6365                 let payment_event = {
6366                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6367                         check_added_monitors!(nodes[0], 1);
6368
6369                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6370                         assert_eq!(events.len(), 1);
6371                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6372                                 assert_eq!(htlcs[0].htlc_id, i);
6373                         } else {
6374                                 assert!(false);
6375                         }
6376                         SendEvent::from_event(events.remove(0))
6377                 };
6378                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6379                 check_added_monitors!(nodes[1], 0);
6380                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6381
6382                 expect_pending_htlcs_forwardable!(nodes[1]);
6383                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6384         }
6385         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6386         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6387                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6388
6389         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6390         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6391 }
6392
6393 #[test]
6394 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6395         //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.
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 channel_value = 100000;
6401         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6402         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6403
6404         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6405
6406         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6407         // Manually create a route over our max in flight (which our router normally automatically
6408         // limits us to.
6409         route.paths[0][0].fee_msat =  max_in_flight + 1;
6410         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6411                 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)));
6412
6413         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6414         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);
6415
6416         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6417 }
6418
6419 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6420 #[test]
6421 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6422         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6423         let chanmon_cfgs = create_chanmon_cfgs(2);
6424         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6425         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6426         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6427         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6428         let htlc_minimum_msat: u64;
6429         {
6430                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6431                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6432                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6433         }
6434
6435         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6436         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6437         check_added_monitors!(nodes[0], 1);
6438         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6439         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6440         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6441         assert!(nodes[1].node.list_channels().is_empty());
6442         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6443         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()));
6444         check_added_monitors!(nodes[1], 1);
6445         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6446 }
6447
6448 #[test]
6449 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6450         //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
6451         let chanmon_cfgs = create_chanmon_cfgs(2);
6452         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6453         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6454         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6455         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6456
6457         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6458         let channel_reserve = chan_stat.channel_reserve_msat;
6459         let feerate = get_feerate!(nodes[0], chan.2);
6460         // The 2* and +1 are for the fee spike reserve.
6461         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6462
6463         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6464         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6465         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6466         check_added_monitors!(nodes[0], 1);
6467         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6468
6469         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6470         // at this time channel-initiatee receivers are not required to enforce that senders
6471         // respect the fee_spike_reserve.
6472         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6473         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6474
6475         assert!(nodes[1].node.list_channels().is_empty());
6476         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6477         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6478         check_added_monitors!(nodes[1], 1);
6479         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6480 }
6481
6482 #[test]
6483 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6484         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6485         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6486         let chanmon_cfgs = create_chanmon_cfgs(2);
6487         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6488         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6489         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6490         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6491
6492         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6493         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6494         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6495         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6496         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6497         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6498
6499         let mut msg = msgs::UpdateAddHTLC {
6500                 channel_id: chan.2,
6501                 htlc_id: 0,
6502                 amount_msat: 1000,
6503                 payment_hash: our_payment_hash,
6504                 cltv_expiry: htlc_cltv,
6505                 onion_routing_packet: onion_packet.clone(),
6506         };
6507
6508         for i in 0..super::channel::OUR_MAX_HTLCS {
6509                 msg.htlc_id = i as u64;
6510                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6511         }
6512         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6513         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6514
6515         assert!(nodes[1].node.list_channels().is_empty());
6516         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6517         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6518         check_added_monitors!(nodes[1], 1);
6519         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6520 }
6521
6522 #[test]
6523 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6524         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6525         let chanmon_cfgs = create_chanmon_cfgs(2);
6526         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6527         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6528         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6529         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6530
6531         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6532         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6533         check_added_monitors!(nodes[0], 1);
6534         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6535         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6536         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6537
6538         assert!(nodes[1].node.list_channels().is_empty());
6539         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6540         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6541         check_added_monitors!(nodes[1], 1);
6542         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6543 }
6544
6545 #[test]
6546 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6547         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6548         let chanmon_cfgs = create_chanmon_cfgs(2);
6549         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6550         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6551         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6552
6553         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6554         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6555         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6556         check_added_monitors!(nodes[0], 1);
6557         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6558         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6559         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6560
6561         assert!(nodes[1].node.list_channels().is_empty());
6562         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6563         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6564         check_added_monitors!(nodes[1], 1);
6565         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6566 }
6567
6568 #[test]
6569 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6570         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6571         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6572         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6573         let chanmon_cfgs = create_chanmon_cfgs(2);
6574         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6575         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6576         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6577
6578         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6579         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6580         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6581         check_added_monitors!(nodes[0], 1);
6582         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6583         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6584
6585         //Disconnect and Reconnect
6586         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6587         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6588         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6589         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6590         assert_eq!(reestablish_1.len(), 1);
6591         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6592         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6593         assert_eq!(reestablish_2.len(), 1);
6594         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6595         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6596         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6597         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6598
6599         //Resend HTLC
6600         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6601         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6602         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6603         check_added_monitors!(nodes[1], 1);
6604         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6605
6606         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6607
6608         assert!(nodes[1].node.list_channels().is_empty());
6609         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6610         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6611         check_added_monitors!(nodes[1], 1);
6612         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6613 }
6614
6615 #[test]
6616 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6617         //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.
6618
6619         let chanmon_cfgs = create_chanmon_cfgs(2);
6620         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6621         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6622         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6623         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6624         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6625         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6626
6627         check_added_monitors!(nodes[0], 1);
6628         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6629         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6630
6631         let update_msg = msgs::UpdateFulfillHTLC{
6632                 channel_id: chan.2,
6633                 htlc_id: 0,
6634                 payment_preimage: our_payment_preimage,
6635         };
6636
6637         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6638
6639         assert!(nodes[0].node.list_channels().is_empty());
6640         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6641         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()));
6642         check_added_monitors!(nodes[0], 1);
6643         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6644 }
6645
6646 #[test]
6647 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6648         //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.
6649
6650         let chanmon_cfgs = create_chanmon_cfgs(2);
6651         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6652         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6653         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6654         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6655
6656         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6657         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6658         check_added_monitors!(nodes[0], 1);
6659         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6660         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6661
6662         let update_msg = msgs::UpdateFailHTLC{
6663                 channel_id: chan.2,
6664                 htlc_id: 0,
6665                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6666         };
6667
6668         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6669
6670         assert!(nodes[0].node.list_channels().is_empty());
6671         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6672         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()));
6673         check_added_monitors!(nodes[0], 1);
6674         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6675 }
6676
6677 #[test]
6678 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6679         //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.
6680
6681         let chanmon_cfgs = create_chanmon_cfgs(2);
6682         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6683         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6684         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6685         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6686
6687         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6688         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6689         check_added_monitors!(nodes[0], 1);
6690         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6691         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6692         let update_msg = msgs::UpdateFailMalformedHTLC{
6693                 channel_id: chan.2,
6694                 htlc_id: 0,
6695                 sha256_of_onion: [1; 32],
6696                 failure_code: 0x8000,
6697         };
6698
6699         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6700
6701         assert!(nodes[0].node.list_channels().is_empty());
6702         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6703         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()));
6704         check_added_monitors!(nodes[0], 1);
6705         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6706 }
6707
6708 #[test]
6709 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6710         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6711
6712         let chanmon_cfgs = create_chanmon_cfgs(2);
6713         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6714         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6715         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6716         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6717
6718         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6719
6720         nodes[1].node.claim_funds(our_payment_preimage);
6721         check_added_monitors!(nodes[1], 1);
6722
6723         let events = nodes[1].node.get_and_clear_pending_msg_events();
6724         assert_eq!(events.len(), 1);
6725         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6726                 match events[0] {
6727                         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, .. } } => {
6728                                 assert!(update_add_htlcs.is_empty());
6729                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6730                                 assert!(update_fail_htlcs.is_empty());
6731                                 assert!(update_fail_malformed_htlcs.is_empty());
6732                                 assert!(update_fee.is_none());
6733                                 update_fulfill_htlcs[0].clone()
6734                         },
6735                         _ => panic!("Unexpected event"),
6736                 }
6737         };
6738
6739         update_fulfill_msg.htlc_id = 1;
6740
6741         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6742
6743         assert!(nodes[0].node.list_channels().is_empty());
6744         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6745         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6746         check_added_monitors!(nodes[0], 1);
6747         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6748 }
6749
6750 #[test]
6751 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6752         //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.
6753
6754         let chanmon_cfgs = create_chanmon_cfgs(2);
6755         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6756         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6757         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6758         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6759
6760         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6761
6762         nodes[1].node.claim_funds(our_payment_preimage);
6763         check_added_monitors!(nodes[1], 1);
6764
6765         let events = nodes[1].node.get_and_clear_pending_msg_events();
6766         assert_eq!(events.len(), 1);
6767         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6768                 match events[0] {
6769                         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, .. } } => {
6770                                 assert!(update_add_htlcs.is_empty());
6771                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6772                                 assert!(update_fail_htlcs.is_empty());
6773                                 assert!(update_fail_malformed_htlcs.is_empty());
6774                                 assert!(update_fee.is_none());
6775                                 update_fulfill_htlcs[0].clone()
6776                         },
6777                         _ => panic!("Unexpected event"),
6778                 }
6779         };
6780
6781         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6782
6783         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6784
6785         assert!(nodes[0].node.list_channels().is_empty());
6786         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6787         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6788         check_added_monitors!(nodes[0], 1);
6789         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6790 }
6791
6792 #[test]
6793 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6794         //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.
6795
6796         let chanmon_cfgs = create_chanmon_cfgs(2);
6797         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6798         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6799         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6800         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6801
6802         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6803         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6804         check_added_monitors!(nodes[0], 1);
6805
6806         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6807         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6808
6809         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6810         check_added_monitors!(nodes[1], 0);
6811         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6812
6813         let events = nodes[1].node.get_and_clear_pending_msg_events();
6814
6815         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6816                 match events[0] {
6817                         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, .. } } => {
6818                                 assert!(update_add_htlcs.is_empty());
6819                                 assert!(update_fulfill_htlcs.is_empty());
6820                                 assert!(update_fail_htlcs.is_empty());
6821                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6822                                 assert!(update_fee.is_none());
6823                                 update_fail_malformed_htlcs[0].clone()
6824                         },
6825                         _ => panic!("Unexpected event"),
6826                 }
6827         };
6828         update_msg.failure_code &= !0x8000;
6829         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6830
6831         assert!(nodes[0].node.list_channels().is_empty());
6832         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6833         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6834         check_added_monitors!(nodes[0], 1);
6835         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6836 }
6837
6838 #[test]
6839 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6840         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6841         //    * 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.
6842
6843         let chanmon_cfgs = create_chanmon_cfgs(3);
6844         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6845         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6846         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6847         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6848         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6849
6850         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6851
6852         //First hop
6853         let mut payment_event = {
6854                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6855                 check_added_monitors!(nodes[0], 1);
6856                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6857                 assert_eq!(events.len(), 1);
6858                 SendEvent::from_event(events.remove(0))
6859         };
6860         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6861         check_added_monitors!(nodes[1], 0);
6862         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6863         expect_pending_htlcs_forwardable!(nodes[1]);
6864         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6865         assert_eq!(events_2.len(), 1);
6866         check_added_monitors!(nodes[1], 1);
6867         payment_event = SendEvent::from_event(events_2.remove(0));
6868         assert_eq!(payment_event.msgs.len(), 1);
6869
6870         //Second Hop
6871         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6872         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6873         check_added_monitors!(nodes[2], 0);
6874         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6875
6876         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6877         assert_eq!(events_3.len(), 1);
6878         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6879                 match events_3[0] {
6880                         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 } } => {
6881                                 assert!(update_add_htlcs.is_empty());
6882                                 assert!(update_fulfill_htlcs.is_empty());
6883                                 assert!(update_fail_htlcs.is_empty());
6884                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6885                                 assert!(update_fee.is_none());
6886                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6887                         },
6888                         _ => panic!("Unexpected event"),
6889                 }
6890         };
6891
6892         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6893
6894         check_added_monitors!(nodes[1], 0);
6895         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6896         expect_pending_htlcs_forwardable!(nodes[1]);
6897         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6898         assert_eq!(events_4.len(), 1);
6899
6900         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6901         match events_4[0] {
6902                 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, .. } } => {
6903                         assert!(update_add_htlcs.is_empty());
6904                         assert!(update_fulfill_htlcs.is_empty());
6905                         assert_eq!(update_fail_htlcs.len(), 1);
6906                         assert!(update_fail_malformed_htlcs.is_empty());
6907                         assert!(update_fee.is_none());
6908                 },
6909                 _ => panic!("Unexpected event"),
6910         };
6911
6912         check_added_monitors!(nodes[1], 1);
6913 }
6914
6915 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6916         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6917         // 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
6918         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6919
6920         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6921         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6922         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6923         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6924         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6925         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6926
6927         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6928
6929         // We route 2 dust-HTLCs between A and B
6930         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6931         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6932         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6933
6934         // Cache one local commitment tx as previous
6935         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6936
6937         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6938         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
6939         check_added_monitors!(nodes[1], 0);
6940         expect_pending_htlcs_forwardable!(nodes[1]);
6941         check_added_monitors!(nodes[1], 1);
6942
6943         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6944         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6945         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6946         check_added_monitors!(nodes[0], 1);
6947
6948         // Cache one local commitment tx as lastest
6949         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6950
6951         let events = nodes[0].node.get_and_clear_pending_msg_events();
6952         match events[0] {
6953                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6954                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6955                 },
6956                 _ => panic!("Unexpected event"),
6957         }
6958         match events[1] {
6959                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6960                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6961                 },
6962                 _ => panic!("Unexpected event"),
6963         }
6964
6965         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6966         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6967         if announce_latest {
6968                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6969         } else {
6970                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6971         }
6972
6973         check_closed_broadcast!(nodes[0], true);
6974         check_added_monitors!(nodes[0], 1);
6975         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6976
6977         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6978         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6979         let events = nodes[0].node.get_and_clear_pending_events();
6980         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6981         assert_eq!(events.len(), 2);
6982         let mut first_failed = false;
6983         for event in events {
6984                 match event {
6985                         Event::PaymentPathFailed { payment_hash, .. } => {
6986                                 if payment_hash == payment_hash_1 {
6987                                         assert!(!first_failed);
6988                                         first_failed = true;
6989                                 } else {
6990                                         assert_eq!(payment_hash, payment_hash_2);
6991                                 }
6992                         }
6993                         _ => panic!("Unexpected event"),
6994                 }
6995         }
6996 }
6997
6998 #[test]
6999 fn test_failure_delay_dust_htlc_local_commitment() {
7000         do_test_failure_delay_dust_htlc_local_commitment(true);
7001         do_test_failure_delay_dust_htlc_local_commitment(false);
7002 }
7003
7004 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7005         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7006         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7007         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7008         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7009         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7010         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7011
7012         let chanmon_cfgs = create_chanmon_cfgs(3);
7013         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7014         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7015         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7016         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7017
7018         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7019
7020         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7021         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7022
7023         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7024         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7025
7026         // We revoked bs_commitment_tx
7027         if revoked {
7028                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7029                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7030         }
7031
7032         let mut timeout_tx = Vec::new();
7033         if local {
7034                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7035                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7036                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7037                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7038                 expect_payment_failed!(nodes[0], dust_hash, true);
7039
7040                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7041                 check_closed_broadcast!(nodes[0], true);
7042                 check_added_monitors!(nodes[0], 1);
7043                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7044                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7045                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7046                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7047                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7048                 mine_transaction(&nodes[0], &timeout_tx[0]);
7049                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7050                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7051         } else {
7052                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7053                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7054                 check_closed_broadcast!(nodes[0], true);
7055                 check_added_monitors!(nodes[0], 1);
7056                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7057                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7058                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7059                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7060                 if !revoked {
7061                         expect_payment_failed!(nodes[0], dust_hash, true);
7062                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7063                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7064                         mine_transaction(&nodes[0], &timeout_tx[0]);
7065                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7066                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7067                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7068                 } else {
7069                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7070                         // commitment tx
7071                         let events = nodes[0].node.get_and_clear_pending_events();
7072                         assert_eq!(events.len(), 2);
7073                         let first;
7074                         match events[0] {
7075                                 Event::PaymentPathFailed { payment_hash, .. } => {
7076                                         if payment_hash == dust_hash { first = true; }
7077                                         else { first = false; }
7078                                 },
7079                                 _ => panic!("Unexpected event"),
7080                         }
7081                         match events[1] {
7082                                 Event::PaymentPathFailed { payment_hash, .. } => {
7083                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7084                                         else { assert_eq!(payment_hash, dust_hash); }
7085                                 },
7086                                 _ => panic!("Unexpected event"),
7087                         }
7088                 }
7089         }
7090 }
7091
7092 #[test]
7093 fn test_sweep_outbound_htlc_failure_update() {
7094         do_test_sweep_outbound_htlc_failure_update(false, true);
7095         do_test_sweep_outbound_htlc_failure_update(false, false);
7096         do_test_sweep_outbound_htlc_failure_update(true, false);
7097 }
7098
7099 #[test]
7100 fn test_user_configurable_csv_delay() {
7101         // We test our channel constructors yield errors when we pass them absurd csv delay
7102
7103         let mut low_our_to_self_config = UserConfig::default();
7104         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7105         let mut high_their_to_self_config = UserConfig::default();
7106         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7107         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7108         let chanmon_cfgs = create_chanmon_cfgs(2);
7109         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7110         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7111         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7112
7113         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7114         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) {
7115                 match error {
7116                         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())); },
7117                         _ => panic!("Unexpected event"),
7118                 }
7119         } else { assert!(false) }
7120
7121         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7122         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7123         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7124         open_channel.to_self_delay = 200;
7125         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) {
7126                 match error {
7127                         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()));  },
7128                         _ => panic!("Unexpected event"),
7129                 }
7130         } else { assert!(false); }
7131
7132         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7133         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7134         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()));
7135         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7136         accept_channel.to_self_delay = 200;
7137         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7138         let reason_msg;
7139         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7140                 match action {
7141                         &ErrorAction::SendErrorMessage { ref msg } => {
7142                                 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()));
7143                                 reason_msg = msg.data.clone();
7144                         },
7145                         _ => { panic!(); }
7146                 }
7147         } else { panic!(); }
7148         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7149
7150         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7151         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7152         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7153         open_channel.to_self_delay = 200;
7154         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) {
7155                 match error {
7156                         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())); },
7157                         _ => panic!("Unexpected event"),
7158                 }
7159         } else { assert!(false); }
7160 }
7161
7162 #[test]
7163 fn test_data_loss_protect() {
7164         // We want to be sure that :
7165         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7166         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7167         // * we close channel in case of detecting other being fallen behind
7168         // * we are able to claim our own outputs thanks to to_remote being static
7169         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7170         let persister;
7171         let logger;
7172         let fee_estimator;
7173         let tx_broadcaster;
7174         let chain_source;
7175         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7176         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7177         // during signing due to revoked tx
7178         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7179         let keys_manager = &chanmon_cfgs[0].keys_manager;
7180         let monitor;
7181         let node_state_0;
7182         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7183         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7184         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7185
7186         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7187
7188         // Cache node A state before any channel update
7189         let previous_node_state = nodes[0].node.encode();
7190         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7191         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7192
7193         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7194         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7195
7196         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7197         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7198
7199         // Restore node A from previous state
7200         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7201         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7202         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7203         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7204         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7205         persister = test_utils::TestPersister::new();
7206         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7207         node_state_0 = {
7208                 let mut channel_monitors = HashMap::new();
7209                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7210                 <(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 {
7211                         keys_manager: keys_manager,
7212                         fee_estimator: &fee_estimator,
7213                         chain_monitor: &monitor,
7214                         logger: &logger,
7215                         tx_broadcaster: &tx_broadcaster,
7216                         default_config: UserConfig::default(),
7217                         channel_monitors,
7218                 }).unwrap().1
7219         };
7220         nodes[0].node = &node_state_0;
7221         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7222         nodes[0].chain_monitor = &monitor;
7223         nodes[0].chain_source = &chain_source;
7224
7225         check_added_monitors!(nodes[0], 1);
7226
7227         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7228         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7229
7230         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7231
7232         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7233         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7234         check_added_monitors!(nodes[0], 1);
7235
7236         {
7237                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7238                 assert_eq!(node_txn.len(), 0);
7239         }
7240
7241         let mut reestablish_1 = Vec::with_capacity(1);
7242         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7243                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7244                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7245                         reestablish_1.push(msg.clone());
7246                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7247                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7248                         match action {
7249                                 &ErrorAction::SendErrorMessage { ref msg } => {
7250                                         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");
7251                                 },
7252                                 _ => panic!("Unexpected event!"),
7253                         }
7254                 } else {
7255                         panic!("Unexpected event")
7256                 }
7257         }
7258
7259         // Check we close channel detecting A is fallen-behind
7260         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7261         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7262         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7263         check_added_monitors!(nodes[1], 1);
7264
7265         // Check A is able to claim to_remote output
7266         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7267         assert_eq!(node_txn.len(), 1);
7268         check_spends!(node_txn[0], chan.3);
7269         assert_eq!(node_txn[0].output.len(), 2);
7270         mine_transaction(&nodes[0], &node_txn[0]);
7271         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7272         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() });
7273         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7274         assert_eq!(spend_txn.len(), 1);
7275         check_spends!(spend_txn[0], node_txn[0]);
7276 }
7277
7278 #[test]
7279 fn test_check_htlc_underpaying() {
7280         // Send payment through A -> B but A is maliciously
7281         // sending a probe payment (i.e less than expected value0
7282         // to B, B should refuse payment.
7283
7284         let chanmon_cfgs = create_chanmon_cfgs(2);
7285         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7286         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7287         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7288
7289         // Create some initial channels
7290         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7291
7292         let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, TEST_FINAL_CLTV, nodes[0].logger).unwrap();
7293         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7294         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, 0).unwrap();
7295         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7296         check_added_monitors!(nodes[0], 1);
7297
7298         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7299         assert_eq!(events.len(), 1);
7300         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7301         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7302         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7303
7304         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7305         // and then will wait a second random delay before failing the HTLC back:
7306         expect_pending_htlcs_forwardable!(nodes[1]);
7307         expect_pending_htlcs_forwardable!(nodes[1]);
7308
7309         // Node 3 is expecting payment of 100_000 but received 10_000,
7310         // it should fail htlc like we didn't know the preimage.
7311         nodes[1].node.process_pending_htlc_forwards();
7312
7313         let events = nodes[1].node.get_and_clear_pending_msg_events();
7314         assert_eq!(events.len(), 1);
7315         let (update_fail_htlc, commitment_signed) = match events[0] {
7316                 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 } } => {
7317                         assert!(update_add_htlcs.is_empty());
7318                         assert!(update_fulfill_htlcs.is_empty());
7319                         assert_eq!(update_fail_htlcs.len(), 1);
7320                         assert!(update_fail_malformed_htlcs.is_empty());
7321                         assert!(update_fee.is_none());
7322                         (update_fail_htlcs[0].clone(), commitment_signed)
7323                 },
7324                 _ => panic!("Unexpected event"),
7325         };
7326         check_added_monitors!(nodes[1], 1);
7327
7328         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7329         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7330
7331         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7332         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7333         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7334         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7335 }
7336
7337 #[test]
7338 fn test_announce_disable_channels() {
7339         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7340         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7341
7342         let chanmon_cfgs = create_chanmon_cfgs(2);
7343         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7344         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7345         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7346
7347         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7348         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7349         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7350
7351         // Disconnect peers
7352         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7353         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7354
7355         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7356         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7357         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7358         assert_eq!(msg_events.len(), 3);
7359         let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7360         for e in msg_events {
7361                 match e {
7362                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7363                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7364                                 // Check that each channel gets updated exactly once
7365                                 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7366                                         panic!("Generated ChannelUpdate for wrong chan!");
7367                                 }
7368                         },
7369                         _ => panic!("Unexpected event"),
7370                 }
7371         }
7372         // Reconnect peers
7373         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7374         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7375         assert_eq!(reestablish_1.len(), 3);
7376         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7377         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7378         assert_eq!(reestablish_2.len(), 3);
7379
7380         // Reestablish chan_1
7381         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7382         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7383         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7384         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7385         // Reestablish chan_2
7386         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7387         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7388         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7389         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7390         // Reestablish chan_3
7391         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7392         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7393         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7394         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7395
7396         nodes[0].node.timer_tick_occurred();
7397         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7398         nodes[0].node.timer_tick_occurred();
7399         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7400         assert_eq!(msg_events.len(), 3);
7401         chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7402         for e in msg_events {
7403                 match e {
7404                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7405                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7406                                 // Check that each channel gets updated exactly once
7407                                 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7408                                         panic!("Generated ChannelUpdate for wrong chan!");
7409                                 }
7410                         },
7411                         _ => panic!("Unexpected event"),
7412                 }
7413         }
7414 }
7415
7416 #[test]
7417 fn test_priv_forwarding_rejection() {
7418         // If we have a private channel with outbound liquidity, and
7419         // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7420         // to forward through that channel.
7421         let chanmon_cfgs = create_chanmon_cfgs(3);
7422         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7423         let mut no_announce_cfg = test_default_channel_config();
7424         no_announce_cfg.channel_options.announced_channel = false;
7425         no_announce_cfg.accept_forwards_to_priv_channels = false;
7426         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7427         let persister: test_utils::TestPersister;
7428         let new_chain_monitor: test_utils::TestChainMonitor;
7429         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7430         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7431
7432         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
7433
7434         // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7435         // not send for private channels.
7436         nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7437         let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7438         nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7439         let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7440         nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7441
7442         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7443         nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7444         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()));
7445         check_added_monitors!(nodes[2], 1);
7446
7447         nodes[1].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[1].node.get_our_node_id()));
7448         check_added_monitors!(nodes[1], 1);
7449
7450         let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7451         confirm_transaction_at(&nodes[1], &tx, conf_height);
7452         connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7453         confirm_transaction_at(&nodes[2], &tx, conf_height);
7454         connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7455         let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7456         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()));
7457         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7458         nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7459         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7460
7461         assert!(nodes[0].node.list_usable_channels()[0].is_public);
7462         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7463         assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7464
7465         // We should always be able to forward through nodes[1] as long as its out through a public
7466         // channel:
7467         send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7468
7469         // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7470         // to nodes[2], which should be rejected:
7471         let route_hint = RouteHint(vec![RouteHintHop {
7472                 src_node_id: nodes[1].node.get_our_node_id(),
7473                 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7474                 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7475                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7476                 htlc_minimum_msat: None,
7477                 htlc_maximum_msat: None,
7478         }]);
7479         let last_hops = vec![&route_hint];
7480         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);
7481
7482         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7483         check_added_monitors!(nodes[0], 1);
7484         let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7485         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7486         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7487
7488         let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7489         assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7490         assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7491         assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7492         assert!(htlc_fail_updates.update_fee.is_none());
7493
7494         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7495         commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7496         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7497
7498         // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7499         // to true. Sadly there is currently no way to change it at runtime.
7500
7501         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7502         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7503
7504         let nodes_1_serialized = nodes[1].node.encode();
7505         let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7506         let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7507         {
7508                 let mons = nodes[1].chain_monitor.chain_monitor.monitors.read().unwrap();
7509                 let mut mon_iter = mons.iter();
7510                 mon_iter.next().unwrap().1.write(&mut monitor_a_serialized).unwrap();
7511                 mon_iter.next().unwrap().1.write(&mut monitor_b_serialized).unwrap();
7512         }
7513
7514         persister = test_utils::TestPersister::new();
7515         let keys_manager = &chanmon_cfgs[1].keys_manager;
7516         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);
7517         nodes[1].chain_monitor = &new_chain_monitor;
7518
7519         let mut monitor_a_read = &monitor_a_serialized.0[..];
7520         let mut monitor_b_read = &monitor_b_serialized.0[..];
7521         let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7522         let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7523         assert!(monitor_a_read.is_empty());
7524         assert!(monitor_b_read.is_empty());
7525
7526         no_announce_cfg.accept_forwards_to_priv_channels = true;
7527
7528         let mut nodes_1_read = &nodes_1_serialized[..];
7529         let (_, nodes_1_deserialized_tmp) = {
7530                 let mut channel_monitors = HashMap::new();
7531                 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7532                 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7533                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7534                         default_config: no_announce_cfg,
7535                         keys_manager,
7536                         fee_estimator: node_cfgs[1].fee_estimator,
7537                         chain_monitor: nodes[1].chain_monitor,
7538                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7539                         logger: nodes[1].logger,
7540                         channel_monitors,
7541                 }).unwrap()
7542         };
7543         assert!(nodes_1_read.is_empty());
7544         nodes_1_deserialized = nodes_1_deserialized_tmp;
7545
7546         assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7547         assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7548         check_added_monitors!(nodes[1], 2);
7549         nodes[1].node = &nodes_1_deserialized;
7550
7551         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7552         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7553         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7554         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7555         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7556         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7557         get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7558         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7559
7560         nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7561         nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7562         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7563         let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7564         nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7565         nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7566         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7567         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7568
7569         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7570         check_added_monitors!(nodes[0], 1);
7571         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7572         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7573 }
7574
7575 #[test]
7576 fn test_bump_penalty_txn_on_revoked_commitment() {
7577         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7578         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7579
7580         let chanmon_cfgs = create_chanmon_cfgs(2);
7581         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7582         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7583         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7584
7585         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7586
7587         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7588         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], vec![], 3000000, 30);
7589         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7590
7591         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7592         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7593         assert_eq!(revoked_txn[0].output.len(), 4);
7594         assert_eq!(revoked_txn[0].input.len(), 1);
7595         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7596         let revoked_txid = revoked_txn[0].txid();
7597
7598         let mut penalty_sum = 0;
7599         for outp in revoked_txn[0].output.iter() {
7600                 if outp.script_pubkey.is_v0_p2wsh() {
7601                         penalty_sum += outp.value;
7602                 }
7603         }
7604
7605         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7606         let header_114 = connect_blocks(&nodes[1], 14);
7607
7608         // Actually revoke tx by claiming a HTLC
7609         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7610         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7611         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7612         check_added_monitors!(nodes[1], 1);
7613
7614         // One or more justice tx should have been broadcast, check it
7615         let penalty_1;
7616         let feerate_1;
7617         {
7618                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7619                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7620                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7621                 assert_eq!(node_txn[0].output.len(), 1);
7622                 check_spends!(node_txn[0], revoked_txn[0]);
7623                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7624                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7625                 penalty_1 = node_txn[0].txid();
7626                 node_txn.clear();
7627         };
7628
7629         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7630         connect_blocks(&nodes[1], 15);
7631         let mut penalty_2 = penalty_1;
7632         let mut feerate_2 = 0;
7633         {
7634                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7635                 assert_eq!(node_txn.len(), 1);
7636                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7637                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7638                         assert_eq!(node_txn[0].output.len(), 1);
7639                         check_spends!(node_txn[0], revoked_txn[0]);
7640                         penalty_2 = node_txn[0].txid();
7641                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7642                         assert_ne!(penalty_2, penalty_1);
7643                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7644                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7645                         // Verify 25% bump heuristic
7646                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7647                         node_txn.clear();
7648                 }
7649         }
7650         assert_ne!(feerate_2, 0);
7651
7652         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7653         connect_blocks(&nodes[1], 1);
7654         let penalty_3;
7655         let mut feerate_3 = 0;
7656         {
7657                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7658                 assert_eq!(node_txn.len(), 1);
7659                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7660                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7661                         assert_eq!(node_txn[0].output.len(), 1);
7662                         check_spends!(node_txn[0], revoked_txn[0]);
7663                         penalty_3 = node_txn[0].txid();
7664                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7665                         assert_ne!(penalty_3, penalty_2);
7666                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7667                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7668                         // Verify 25% bump heuristic
7669                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7670                         node_txn.clear();
7671                 }
7672         }
7673         assert_ne!(feerate_3, 0);
7674
7675         nodes[1].node.get_and_clear_pending_events();
7676         nodes[1].node.get_and_clear_pending_msg_events();
7677 }
7678
7679 #[test]
7680 fn test_bump_penalty_txn_on_revoked_htlcs() {
7681         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7682         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7683
7684         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7685         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7686         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7687         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7688         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7689
7690         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7691         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7692         let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph,
7693                 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7694         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7695         let route = get_route(&nodes[1].node.get_our_node_id(), &nodes[1].net_graph_msg_handler.network_graph,
7696                 &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7697         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7698
7699         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7700         assert_eq!(revoked_local_txn[0].input.len(), 1);
7701         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7702
7703         // Revoke local commitment tx
7704         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7705
7706         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7707         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7708         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7709         check_closed_broadcast!(nodes[1], true);
7710         check_added_monitors!(nodes[1], 1);
7711         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7712         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7713
7714         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7715         assert_eq!(revoked_htlc_txn.len(), 3);
7716         check_spends!(revoked_htlc_txn[1], chan.3);
7717
7718         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7719         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7720         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7721
7722         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7723         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7724         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7725         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7726
7727         // Broadcast set of revoked txn on A
7728         let hash_128 = connect_blocks(&nodes[0], 40);
7729         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7730         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7731         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7732         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7733         let events = nodes[0].node.get_and_clear_pending_events();
7734         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7735         match events[1] {
7736                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7737                 _ => panic!("Unexpected event"),
7738         }
7739         let first;
7740         let feerate_1;
7741         let penalty_txn;
7742         {
7743                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7744                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7745                 // Verify claim tx are spending revoked HTLC txn
7746
7747                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7748                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7749                 // which are included in the same block (they are broadcasted because we scan the
7750                 // transactions linearly and generate claims as we go, they likely should be removed in the
7751                 // future).
7752                 assert_eq!(node_txn[0].input.len(), 1);
7753                 check_spends!(node_txn[0], revoked_local_txn[0]);
7754                 assert_eq!(node_txn[1].input.len(), 1);
7755                 check_spends!(node_txn[1], revoked_local_txn[0]);
7756                 assert_eq!(node_txn[2].input.len(), 1);
7757                 check_spends!(node_txn[2], revoked_local_txn[0]);
7758
7759                 // Each of the three justice transactions claim a separate (single) output of the three
7760                 // available, which we check here:
7761                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7762                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7763                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7764
7765                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7766                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7767
7768                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7769                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7770                 // a remote commitment tx has already been confirmed).
7771                 check_spends!(node_txn[3], chan.3);
7772
7773                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7774                 // output, checked above).
7775                 assert_eq!(node_txn[4].input.len(), 2);
7776                 assert_eq!(node_txn[4].output.len(), 1);
7777                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7778
7779                 first = node_txn[4].txid();
7780                 // Store both feerates for later comparison
7781                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7782                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7783                 penalty_txn = vec![node_txn[2].clone()];
7784                 node_txn.clear();
7785         }
7786
7787         // Connect one more block to see if bumped penalty are issued for HTLC txn
7788         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7789         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7790         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7791         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7792         {
7793                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7794                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7795
7796                 check_spends!(node_txn[0], revoked_local_txn[0]);
7797                 check_spends!(node_txn[1], revoked_local_txn[0]);
7798                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7799                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7800                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7801                 } else {
7802                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7803                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7804                 }
7805
7806                 node_txn.clear();
7807         };
7808
7809         // Few more blocks to confirm penalty txn
7810         connect_blocks(&nodes[0], 4);
7811         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7812         let header_144 = connect_blocks(&nodes[0], 9);
7813         let node_txn = {
7814                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7815                 assert_eq!(node_txn.len(), 1);
7816
7817                 assert_eq!(node_txn[0].input.len(), 2);
7818                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7819                 // Verify bumped tx is different and 25% bump heuristic
7820                 assert_ne!(first, node_txn[0].txid());
7821                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7822                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7823                 assert!(feerate_2 * 100 > feerate_1 * 125);
7824                 let txn = vec![node_txn[0].clone()];
7825                 node_txn.clear();
7826                 txn
7827         };
7828         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7829         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7830         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7831         connect_blocks(&nodes[0], 20);
7832         {
7833                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7834                 // We verify than no new transaction has been broadcast because previously
7835                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7836                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7837                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7838                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7839                 // up bumped justice generation.
7840                 assert_eq!(node_txn.len(), 0);
7841                 node_txn.clear();
7842         }
7843         check_closed_broadcast!(nodes[0], true);
7844         check_added_monitors!(nodes[0], 1);
7845 }
7846
7847 #[test]
7848 fn test_bump_penalty_txn_on_remote_commitment() {
7849         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7850         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7851
7852         // Create 2 HTLCs
7853         // Provide preimage for one
7854         // Check aggregation
7855
7856         let chanmon_cfgs = create_chanmon_cfgs(2);
7857         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7858         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7859         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7860
7861         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7862         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7863         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7864
7865         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7866         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7867         assert_eq!(remote_txn[0].output.len(), 4);
7868         assert_eq!(remote_txn[0].input.len(), 1);
7869         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7870
7871         // Claim a HTLC without revocation (provide B monitor with preimage)
7872         nodes[1].node.claim_funds(payment_preimage);
7873         mine_transaction(&nodes[1], &remote_txn[0]);
7874         check_added_monitors!(nodes[1], 2);
7875         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7876
7877         // One or more claim tx should have been broadcast, check it
7878         let timeout;
7879         let preimage;
7880         let preimage_bump;
7881         let feerate_timeout;
7882         let feerate_preimage;
7883         {
7884                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7885                 // 9 transactions including:
7886                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7887                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7888                 // 2 * HTLC-Success (one RBF bump we'll check later)
7889                 // 1 * HTLC-Timeout
7890                 assert_eq!(node_txn.len(), 8);
7891                 assert_eq!(node_txn[0].input.len(), 1);
7892                 assert_eq!(node_txn[6].input.len(), 1);
7893                 check_spends!(node_txn[0], remote_txn[0]);
7894                 check_spends!(node_txn[6], remote_txn[0]);
7895                 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7896                 preimage_bump = node_txn[3].clone();
7897
7898                 check_spends!(node_txn[1], chan.3);
7899                 check_spends!(node_txn[2], node_txn[1]);
7900                 assert_eq!(node_txn[1], node_txn[4]);
7901                 assert_eq!(node_txn[2], node_txn[5]);
7902
7903                 timeout = node_txn[6].txid();
7904                 let index = node_txn[6].input[0].previous_output.vout;
7905                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7906                 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7907
7908                 preimage = node_txn[0].txid();
7909                 let index = node_txn[0].input[0].previous_output.vout;
7910                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7911                 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7912
7913                 node_txn.clear();
7914         };
7915         assert_ne!(feerate_timeout, 0);
7916         assert_ne!(feerate_preimage, 0);
7917
7918         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7919         connect_blocks(&nodes[1], 15);
7920         {
7921                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7922                 assert_eq!(node_txn.len(), 1);
7923                 assert_eq!(node_txn[0].input.len(), 1);
7924                 assert_eq!(preimage_bump.input.len(), 1);
7925                 check_spends!(node_txn[0], remote_txn[0]);
7926                 check_spends!(preimage_bump, remote_txn[0]);
7927
7928                 let index = preimage_bump.input[0].previous_output.vout;
7929                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7930                 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7931                 assert!(new_feerate * 100 > feerate_timeout * 125);
7932                 assert_ne!(timeout, preimage_bump.txid());
7933
7934                 let index = node_txn[0].input[0].previous_output.vout;
7935                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7936                 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7937                 assert!(new_feerate * 100 > feerate_preimage * 125);
7938                 assert_ne!(preimage, node_txn[0].txid());
7939
7940                 node_txn.clear();
7941         }
7942
7943         nodes[1].node.get_and_clear_pending_events();
7944         nodes[1].node.get_and_clear_pending_msg_events();
7945 }
7946
7947 #[test]
7948 fn test_counterparty_raa_skip_no_crash() {
7949         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7950         // commitment transaction, we would have happily carried on and provided them the next
7951         // commitment transaction based on one RAA forward. This would probably eventually have led to
7952         // channel closure, but it would not have resulted in funds loss. Still, our
7953         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7954         // check simply that the channel is closed in response to such an RAA, but don't check whether
7955         // we decide to punish our counterparty for revoking their funds (as we don't currently
7956         // implement that).
7957         let chanmon_cfgs = create_chanmon_cfgs(2);
7958         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7959         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7960         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7961         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7962
7963         let mut guard = nodes[0].node.channel_state.lock().unwrap();
7964         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7965
7966         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7967
7968         // Make signer believe we got a counterparty signature, so that it allows the revocation
7969         keys.get_enforcement_state().last_holder_commitment -= 1;
7970         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7971
7972         // Must revoke without gaps
7973         keys.get_enforcement_state().last_holder_commitment -= 1;
7974         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7975
7976         keys.get_enforcement_state().last_holder_commitment -= 1;
7977         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7978                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7979
7980         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7981                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7982         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7983         check_added_monitors!(nodes[1], 1);
7984         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7985 }
7986
7987 #[test]
7988 fn test_bump_txn_sanitize_tracking_maps() {
7989         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7990         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7991
7992         let chanmon_cfgs = create_chanmon_cfgs(2);
7993         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7994         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7995         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7996
7997         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7998         // Lock HTLC in both directions
7999         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8000         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8001
8002         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8003         assert_eq!(revoked_local_txn[0].input.len(), 1);
8004         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8005
8006         // Revoke local commitment tx
8007         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8008
8009         // Broadcast set of revoked txn on A
8010         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8011         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8012         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8013
8014         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8015         check_closed_broadcast!(nodes[0], true);
8016         check_added_monitors!(nodes[0], 1);
8017         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8018         let penalty_txn = {
8019                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8020                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8021                 check_spends!(node_txn[0], revoked_local_txn[0]);
8022                 check_spends!(node_txn[1], revoked_local_txn[0]);
8023                 check_spends!(node_txn[2], revoked_local_txn[0]);
8024                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8025                 node_txn.clear();
8026                 penalty_txn
8027         };
8028         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8029         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8030         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8031         {
8032                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8033                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8034                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8035                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8036                 }
8037         }
8038 }
8039
8040 #[test]
8041 fn test_override_channel_config() {
8042         let chanmon_cfgs = create_chanmon_cfgs(2);
8043         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8044         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8045         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8046
8047         // Node0 initiates a channel to node1 using the override config.
8048         let mut override_config = UserConfig::default();
8049         override_config.own_channel_config.our_to_self_delay = 200;
8050
8051         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8052
8053         // Assert the channel created by node0 is using the override config.
8054         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8055         assert_eq!(res.channel_flags, 0);
8056         assert_eq!(res.to_self_delay, 200);
8057 }
8058
8059 #[test]
8060 fn test_override_0msat_htlc_minimum() {
8061         let mut zero_config = UserConfig::default();
8062         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8063         let chanmon_cfgs = create_chanmon_cfgs(2);
8064         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8065         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8066         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8067
8068         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8069         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8070         assert_eq!(res.htlc_minimum_msat, 1);
8071
8072         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8073         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8074         assert_eq!(res.htlc_minimum_msat, 1);
8075 }
8076
8077 #[test]
8078 fn test_simple_mpp() {
8079         // Simple test of sending a multi-path payment.
8080         let chanmon_cfgs = create_chanmon_cfgs(4);
8081         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8082         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8083         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8084
8085         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8086         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8087         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8088         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8089
8090         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8091         let path = route.paths[0].clone();
8092         route.paths.push(path);
8093         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8094         route.paths[0][0].short_channel_id = chan_1_id;
8095         route.paths[0][1].short_channel_id = chan_3_id;
8096         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8097         route.paths[1][0].short_channel_id = chan_2_id;
8098         route.paths[1][1].short_channel_id = chan_4_id;
8099         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8100         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8101 }
8102
8103 #[test]
8104 fn test_preimage_storage() {
8105         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8106         let chanmon_cfgs = create_chanmon_cfgs(2);
8107         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8108         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8109         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8110
8111         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8112
8113         {
8114                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, 42);
8115                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8116                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8117                 check_added_monitors!(nodes[0], 1);
8118                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8119                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8120                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8121                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8122         }
8123         // Note that after leaving the above scope we have no knowledge of any arguments or return
8124         // values from previous calls.
8125         expect_pending_htlcs_forwardable!(nodes[1]);
8126         let events = nodes[1].node.get_and_clear_pending_events();
8127         assert_eq!(events.len(), 1);
8128         match events[0] {
8129                 Event::PaymentReceived { ref purpose, .. } => {
8130                         match &purpose {
8131                                 PaymentPurpose::InvoicePayment { payment_preimage, user_payment_id, .. } => {
8132                                         assert_eq!(*user_payment_id, 42);
8133                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8134                                 },
8135                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8136                         }
8137                 },
8138                 _ => panic!("Unexpected event"),
8139         }
8140 }
8141
8142 #[test]
8143 fn test_secret_timeout() {
8144         // Simple test of payment secret storage time outs
8145         let chanmon_cfgs = create_chanmon_cfgs(2);
8146         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8147         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8148         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8149
8150         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8151
8152         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8153
8154         // We should fail to register the same payment hash twice, at least until we've connected a
8155         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8156         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8157                 assert_eq!(err, "Duplicate payment hash");
8158         } else { panic!(); }
8159         let mut block = {
8160                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8161                 Block {
8162                         header: BlockHeader {
8163                                 version: 0x2000000,
8164                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8165                                 merkle_root: Default::default(),
8166                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8167                         txdata: vec![],
8168                 }
8169         };
8170         connect_block(&nodes[1], &block);
8171         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8172                 assert_eq!(err, "Duplicate payment hash");
8173         } else { panic!(); }
8174
8175         // If we then connect the second block, we should be able to register the same payment hash
8176         // again with a different user_payment_id (this time getting a new payment secret).
8177         block.header.prev_blockhash = block.header.block_hash();
8178         block.header.time += 1;
8179         connect_block(&nodes[1], &block);
8180         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 42).unwrap();
8181         assert_ne!(payment_secret_1, our_payment_secret);
8182
8183         {
8184                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8185                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8186                 check_added_monitors!(nodes[0], 1);
8187                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8188                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8189                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8190                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8191         }
8192         // Note that after leaving the above scope we have no knowledge of any arguments or return
8193         // values from previous calls.
8194         expect_pending_htlcs_forwardable!(nodes[1]);
8195         let events = nodes[1].node.get_and_clear_pending_events();
8196         assert_eq!(events.len(), 1);
8197         match events[0] {
8198                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, user_payment_id }, .. } => {
8199                         assert!(payment_preimage.is_none());
8200                         assert_eq!(user_payment_id, 42);
8201                         assert_eq!(payment_secret, our_payment_secret);
8202                         // We don't actually have the payment preimage with which to claim this payment!
8203                 },
8204                 _ => panic!("Unexpected event"),
8205         }
8206 }
8207
8208 #[test]
8209 fn test_bad_secret_hash() {
8210         // Simple test of unregistered payment hash/invalid payment secret handling
8211         let chanmon_cfgs = create_chanmon_cfgs(2);
8212         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8213         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8214         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8215
8216         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8217
8218         let random_payment_hash = PaymentHash([42; 32]);
8219         let random_payment_secret = PaymentSecret([43; 32]);
8220         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8221         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8222
8223         // All the below cases should end up being handled exactly identically, so we macro the
8224         // resulting events.
8225         macro_rules! handle_unknown_invalid_payment_data {
8226                 () => {
8227                         check_added_monitors!(nodes[0], 1);
8228                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8229                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8230                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8231                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8232
8233                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8234                         // again to process the pending backwards-failure of the HTLC
8235                         expect_pending_htlcs_forwardable!(nodes[1]);
8236                         expect_pending_htlcs_forwardable!(nodes[1]);
8237                         check_added_monitors!(nodes[1], 1);
8238
8239                         // We should fail the payment back
8240                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8241                         match events.pop().unwrap() {
8242                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8243                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8244                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8245                                 },
8246                                 _ => panic!("Unexpected event"),
8247                         }
8248                 }
8249         }
8250
8251         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8252         // Error data is the HTLC value (100,000) and current block height
8253         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8254
8255         // Send a payment with the right payment hash but the wrong payment secret
8256         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8257         handle_unknown_invalid_payment_data!();
8258         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8259
8260         // Send a payment with a random payment hash, but the right payment secret
8261         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8262         handle_unknown_invalid_payment_data!();
8263         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8264
8265         // Send a payment with a random payment hash and random payment secret
8266         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8267         handle_unknown_invalid_payment_data!();
8268         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8269 }
8270
8271 #[test]
8272 fn test_update_err_monitor_lockdown() {
8273         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8274         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8275         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8276         //
8277         // This scenario may happen in a watchtower setup, where watchtower process a block height
8278         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8279         // commitment at same time.
8280
8281         let chanmon_cfgs = create_chanmon_cfgs(2);
8282         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8283         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8284         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8285
8286         // Create some initial channel
8287         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8288         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8289
8290         // Rebalance the network to generate htlc in the two directions
8291         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8292
8293         // Route a HTLC from node 0 to node 1 (but don't settle)
8294         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8295
8296         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8297         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8298         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8299         let persister = test_utils::TestPersister::new();
8300         let watchtower = {
8301                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8302                 let monitor = monitors.get(&outpoint).unwrap();
8303                 let mut w = test_utils::TestVecWriter(Vec::new());
8304                 monitor.write(&mut w).unwrap();
8305                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8306                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8307                 assert!(new_monitor == *monitor);
8308                 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);
8309                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8310                 watchtower
8311         };
8312         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8313         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8314         // transaction lock time requirements here.
8315         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8316         watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8317
8318         // Try to update ChannelMonitor
8319         assert!(nodes[1].node.claim_funds(preimage));
8320         check_added_monitors!(nodes[1], 1);
8321         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8322         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8323         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8324         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8325                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8326                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8327                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8328                 } else { assert!(false); }
8329         } else { assert!(false); };
8330         // Our local monitor is in-sync and hasn't processed yet timeout
8331         check_added_monitors!(nodes[0], 1);
8332         let events = nodes[0].node.get_and_clear_pending_events();
8333         assert_eq!(events.len(), 1);
8334 }
8335
8336 #[test]
8337 fn test_concurrent_monitor_claim() {
8338         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8339         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8340         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8341         // state N+1 confirms. Alice claims output from state N+1.
8342
8343         let chanmon_cfgs = create_chanmon_cfgs(2);
8344         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8345         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8346         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8347
8348         // Create some initial channel
8349         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8350         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8351
8352         // Rebalance the network to generate htlc in the two directions
8353         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8354
8355         // Route a HTLC from node 0 to node 1 (but don't settle)
8356         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8357
8358         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8359         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8360         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8361         let persister = test_utils::TestPersister::new();
8362         let watchtower_alice = {
8363                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8364                 let monitor = monitors.get(&outpoint).unwrap();
8365                 let mut w = test_utils::TestVecWriter(Vec::new());
8366                 monitor.write(&mut w).unwrap();
8367                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8368                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8369                 assert!(new_monitor == *monitor);
8370                 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);
8371                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8372                 watchtower
8373         };
8374         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8375         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8376         // transaction lock time requirements here.
8377         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8378         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8379
8380         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8381         {
8382                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8383                 assert_eq!(txn.len(), 2);
8384                 txn.clear();
8385         }
8386
8387         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8388         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8389         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8390         let persister = test_utils::TestPersister::new();
8391         let watchtower_bob = {
8392                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8393                 let monitor = monitors.get(&outpoint).unwrap();
8394                 let mut w = test_utils::TestVecWriter(Vec::new());
8395                 monitor.write(&mut w).unwrap();
8396                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8397                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8398                 assert!(new_monitor == *monitor);
8399                 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);
8400                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8401                 watchtower
8402         };
8403         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8404         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8405
8406         // Route another payment to generate another update with still previous HTLC pending
8407         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8408         {
8409                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8410         }
8411         check_added_monitors!(nodes[1], 1);
8412
8413         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8414         assert_eq!(updates.update_add_htlcs.len(), 1);
8415         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8416         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8417                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8418                         // Watchtower Alice should already have seen the block and reject the update
8419                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8420                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8421                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8422                 } else { assert!(false); }
8423         } else { assert!(false); };
8424         // Our local monitor is in-sync and hasn't processed yet timeout
8425         check_added_monitors!(nodes[0], 1);
8426
8427         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8428         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8429         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8430
8431         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8432         let bob_state_y;
8433         {
8434                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8435                 assert_eq!(txn.len(), 2);
8436                 bob_state_y = txn[0].clone();
8437                 txn.clear();
8438         };
8439
8440         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8441         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8442         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);
8443         {
8444                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8445                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8446                 // the onchain detection of the HTLC output
8447                 assert_eq!(htlc_txn.len(), 2);
8448                 check_spends!(htlc_txn[0], bob_state_y);
8449                 check_spends!(htlc_txn[1], bob_state_y);
8450         }
8451 }
8452
8453 #[test]
8454 fn test_pre_lockin_no_chan_closed_update() {
8455         // Test that if a peer closes a channel in response to a funding_created message we don't
8456         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8457         // message).
8458         //
8459         // Doing so would imply a channel monitor update before the initial channel monitor
8460         // registration, violating our API guarantees.
8461         //
8462         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8463         // then opening a second channel with the same funding output as the first (which is not
8464         // rejected because the first channel does not exist in the ChannelManager) and closing it
8465         // before receiving funding_signed.
8466         let chanmon_cfgs = create_chanmon_cfgs(2);
8467         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8468         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8469         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8470
8471         // Create an initial channel
8472         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8473         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8474         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8475         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8476         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8477
8478         // Move the first channel through the funding flow...
8479         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8480
8481         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8482         check_added_monitors!(nodes[0], 0);
8483
8484         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8485         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8486         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8487         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8488         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8489 }
8490
8491 #[test]
8492 fn test_htlc_no_detection() {
8493         // This test is a mutation to underscore the detection logic bug we had
8494         // before #653. HTLC value routed is above the remaining balance, thus
8495         // inverting HTLC and `to_remote` output. HTLC will come second and
8496         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8497         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8498         // outputs order detection for correct spending children filtring.
8499
8500         let chanmon_cfgs = create_chanmon_cfgs(2);
8501         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8502         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8503         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8504
8505         // Create some initial channels
8506         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8507
8508         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8509         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8510         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8511         assert_eq!(local_txn[0].input.len(), 1);
8512         assert_eq!(local_txn[0].output.len(), 3);
8513         check_spends!(local_txn[0], chan_1.3);
8514
8515         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8516         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8517         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8518         // We deliberately connect the local tx twice as this should provoke a failure calling
8519         // this test before #653 fix.
8520         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);
8521         check_closed_broadcast!(nodes[0], true);
8522         check_added_monitors!(nodes[0], 1);
8523         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8524         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8525
8526         let htlc_timeout = {
8527                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8528                 assert_eq!(node_txn[1].input.len(), 1);
8529                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8530                 check_spends!(node_txn[1], local_txn[0]);
8531                 node_txn[1].clone()
8532         };
8533
8534         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8535         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8536         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8537         expect_payment_failed!(nodes[0], our_payment_hash, true);
8538 }
8539
8540 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8541         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8542         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8543         // Carol, Alice would be the upstream node, and Carol the downstream.)
8544         //
8545         // Steps of the test:
8546         // 1) Alice sends a HTLC to Carol through Bob.
8547         // 2) Carol doesn't settle the HTLC.
8548         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8549         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8550         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8551         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8552         // 5) Carol release the preimage to Bob off-chain.
8553         // 6) Bob claims the offered output on the broadcasted commitment.
8554         let chanmon_cfgs = create_chanmon_cfgs(3);
8555         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8556         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8557         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8558
8559         // Create some initial channels
8560         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8561         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8562
8563         // Steps (1) and (2):
8564         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8565         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8566
8567         // Check that Alice's commitment transaction now contains an output for this HTLC.
8568         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8569         check_spends!(alice_txn[0], chan_ab.3);
8570         assert_eq!(alice_txn[0].output.len(), 2);
8571         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8572         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8573         assert_eq!(alice_txn.len(), 2);
8574
8575         // Steps (3) and (4):
8576         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8577         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8578         let mut force_closing_node = 0; // Alice force-closes
8579         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8580         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8581         check_closed_broadcast!(nodes[force_closing_node], true);
8582         check_added_monitors!(nodes[force_closing_node], 1);
8583         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8584         if go_onchain_before_fulfill {
8585                 let txn_to_broadcast = match broadcast_alice {
8586                         true => alice_txn.clone(),
8587                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8588                 };
8589                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8590                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8591                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8592                 if broadcast_alice {
8593                         check_closed_broadcast!(nodes[1], true);
8594                         check_added_monitors!(nodes[1], 1);
8595                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8596                 }
8597                 assert_eq!(bob_txn.len(), 1);
8598                 check_spends!(bob_txn[0], chan_ab.3);
8599         }
8600
8601         // Step (5):
8602         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8603         // process of removing the HTLC from their commitment transactions.
8604         assert!(nodes[2].node.claim_funds(payment_preimage));
8605         check_added_monitors!(nodes[2], 1);
8606         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8607         assert!(carol_updates.update_add_htlcs.is_empty());
8608         assert!(carol_updates.update_fail_htlcs.is_empty());
8609         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8610         assert!(carol_updates.update_fee.is_none());
8611         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8612
8613         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8614         expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8615         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8616         if !go_onchain_before_fulfill && broadcast_alice {
8617                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8618                 assert_eq!(events.len(), 1);
8619                 match events[0] {
8620                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8621                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8622                         },
8623                         _ => panic!("Unexpected event"),
8624                 };
8625         }
8626         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8627         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8628         // Carol<->Bob's updated commitment transaction info.
8629         check_added_monitors!(nodes[1], 2);
8630
8631         let events = nodes[1].node.get_and_clear_pending_msg_events();
8632         assert_eq!(events.len(), 2);
8633         let bob_revocation = match events[0] {
8634                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8635                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8636                         (*msg).clone()
8637                 },
8638                 _ => panic!("Unexpected event"),
8639         };
8640         let bob_updates = match events[1] {
8641                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8642                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8643                         (*updates).clone()
8644                 },
8645                 _ => panic!("Unexpected event"),
8646         };
8647
8648         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8649         check_added_monitors!(nodes[2], 1);
8650         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8651         check_added_monitors!(nodes[2], 1);
8652
8653         let events = nodes[2].node.get_and_clear_pending_msg_events();
8654         assert_eq!(events.len(), 1);
8655         let carol_revocation = match events[0] {
8656                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8657                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8658                         (*msg).clone()
8659                 },
8660                 _ => panic!("Unexpected event"),
8661         };
8662         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8663         check_added_monitors!(nodes[1], 1);
8664
8665         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8666         // here's where we put said channel's commitment tx on-chain.
8667         let mut txn_to_broadcast = alice_txn.clone();
8668         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8669         if !go_onchain_before_fulfill {
8670                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8671                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8672                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8673                 if broadcast_alice {
8674                         check_closed_broadcast!(nodes[1], true);
8675                         check_added_monitors!(nodes[1], 1);
8676                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8677                 }
8678                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8679                 if broadcast_alice {
8680                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8681                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8682                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8683                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8684                         // broadcasted.
8685                         assert_eq!(bob_txn.len(), 3);
8686                         check_spends!(bob_txn[1], chan_ab.3);
8687                 } else {
8688                         assert_eq!(bob_txn.len(), 2);
8689                         check_spends!(bob_txn[0], chan_ab.3);
8690                 }
8691         }
8692
8693         // Step (6):
8694         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8695         // broadcasted commitment transaction.
8696         {
8697                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8698                 if go_onchain_before_fulfill {
8699                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8700                         assert_eq!(bob_txn.len(), 2);
8701                 }
8702                 let script_weight = match broadcast_alice {
8703                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8704                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8705                 };
8706                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8707                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8708                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8709                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8710                 if broadcast_alice && !go_onchain_before_fulfill {
8711                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8712                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8713                 } else {
8714                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8715                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8716                 }
8717         }
8718 }
8719
8720 #[test]
8721 fn test_onchain_htlc_settlement_after_close() {
8722         do_test_onchain_htlc_settlement_after_close(true, true);
8723         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8724         do_test_onchain_htlc_settlement_after_close(true, false);
8725         do_test_onchain_htlc_settlement_after_close(false, false);
8726 }
8727
8728 #[test]
8729 fn test_duplicate_chan_id() {
8730         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8731         // already open we reject it and keep the old channel.
8732         //
8733         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8734         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8735         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8736         // updating logic for the existing channel.
8737         let chanmon_cfgs = create_chanmon_cfgs(2);
8738         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8739         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8740         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8741
8742         // Create an initial channel
8743         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8744         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8745         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8746         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()));
8747
8748         // Try to create a second channel with the same temporary_channel_id as the first and check
8749         // that it is rejected.
8750         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8751         {
8752                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8753                 assert_eq!(events.len(), 1);
8754                 match events[0] {
8755                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8756                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8757                                 // first (valid) and second (invalid) channels are closed, given they both have
8758                                 // the same non-temporary channel_id. However, currently we do not, so we just
8759                                 // move forward with it.
8760                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8761                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8762                         },
8763                         _ => panic!("Unexpected event"),
8764                 }
8765         }
8766
8767         // Move the first channel through the funding flow...
8768         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8769
8770         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8771         check_added_monitors!(nodes[0], 0);
8772
8773         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8774         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8775         {
8776                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8777                 assert_eq!(added_monitors.len(), 1);
8778                 assert_eq!(added_monitors[0].0, funding_output);
8779                 added_monitors.clear();
8780         }
8781         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8782
8783         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8784         let channel_id = funding_outpoint.to_channel_id();
8785
8786         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8787         // temporary one).
8788
8789         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8790         // Technically this is allowed by the spec, but we don't support it and there's little reason
8791         // to. Still, it shouldn't cause any other issues.
8792         open_chan_msg.temporary_channel_id = channel_id;
8793         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8794         {
8795                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8796                 assert_eq!(events.len(), 1);
8797                 match events[0] {
8798                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8799                                 // Technically, at this point, nodes[1] would be justified in thinking both
8800                                 // channels are closed, but currently we do not, so we just move forward with it.
8801                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8802                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8803                         },
8804                         _ => panic!("Unexpected event"),
8805                 }
8806         }
8807
8808         // Now try to create a second channel which has a duplicate funding output.
8809         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8810         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8811         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
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         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8814
8815         let funding_created = {
8816                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8817                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8818                 let logger = test_utils::TestLogger::new();
8819                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8820         };
8821         check_added_monitors!(nodes[0], 0);
8822         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8823         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8824         // still needs to be cleared here.
8825         check_added_monitors!(nodes[1], 1);
8826
8827         // ...still, nodes[1] will reject the duplicate channel.
8828         {
8829                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8830                 assert_eq!(events.len(), 1);
8831                 match events[0] {
8832                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8833                                 // Technically, at this point, nodes[1] would be justified in thinking both
8834                                 // channels are closed, but currently we do not, so we just move forward with it.
8835                                 assert_eq!(msg.channel_id, channel_id);
8836                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8837                         },
8838                         _ => panic!("Unexpected event"),
8839                 }
8840         }
8841
8842         // finally, finish creating the original channel and send a payment over it to make sure
8843         // everything is functional.
8844         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8845         {
8846                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8847                 assert_eq!(added_monitors.len(), 1);
8848                 assert_eq!(added_monitors[0].0, funding_output);
8849                 added_monitors.clear();
8850         }
8851
8852         let events_4 = nodes[0].node.get_and_clear_pending_events();
8853         assert_eq!(events_4.len(), 0);
8854         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8855         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8856
8857         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8858         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8859         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8860         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8861 }
8862
8863 #[test]
8864 fn test_error_chans_closed() {
8865         // Test that we properly handle error messages, closing appropriate channels.
8866         //
8867         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8868         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8869         // we can test various edge cases around it to ensure we don't regress.
8870         let chanmon_cfgs = create_chanmon_cfgs(3);
8871         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8872         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8873         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8874
8875         // Create some initial channels
8876         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8877         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8878         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8879
8880         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8881         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8882         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8883
8884         // Closing a channel from a different peer has no effect
8885         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8886         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8887
8888         // Closing one channel doesn't impact others
8889         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8890         check_added_monitors!(nodes[0], 1);
8891         check_closed_broadcast!(nodes[0], false);
8892         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8893         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8894         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8895         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);
8896         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);
8897
8898         // A null channel ID should close all channels
8899         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8900         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8901         check_added_monitors!(nodes[0], 2);
8902         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8903         let events = nodes[0].node.get_and_clear_pending_msg_events();
8904         assert_eq!(events.len(), 2);
8905         match events[0] {
8906                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8907                         assert_eq!(msg.contents.flags & 2, 2);
8908                 },
8909                 _ => panic!("Unexpected event"),
8910         }
8911         match events[1] {
8912                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8913                         assert_eq!(msg.contents.flags & 2, 2);
8914                 },
8915                 _ => panic!("Unexpected event"),
8916         }
8917         // Note that at this point users of a standard PeerHandler will end up calling
8918         // peer_disconnected with no_connection_possible set to false, duplicating the
8919         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8920         // users with their own peer handling logic. We duplicate the call here, however.
8921         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8922         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8923
8924         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8925         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8926         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8927 }
8928
8929 #[test]
8930 fn test_invalid_funding_tx() {
8931         // Test that we properly handle invalid funding transactions sent to us from a peer.
8932         //
8933         // Previously, all other major lightning implementations had failed to properly sanitize
8934         // funding transactions from their counterparties, leading to a multi-implementation critical
8935         // security vulnerability (though we always sanitized properly, we've previously had
8936         // un-released crashes in the sanitization process).
8937         let chanmon_cfgs = create_chanmon_cfgs(2);
8938         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8939         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8940         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8941
8942         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8943         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()));
8944         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()));
8945
8946         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
8947         for output in tx.output.iter_mut() {
8948                 // Make the confirmed funding transaction have a bogus script_pubkey
8949                 output.script_pubkey = bitcoin::Script::new();
8950         }
8951
8952         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
8953         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()));
8954         check_added_monitors!(nodes[1], 1);
8955
8956         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()));
8957         check_added_monitors!(nodes[0], 1);
8958
8959         let events_1 = nodes[0].node.get_and_clear_pending_events();
8960         assert_eq!(events_1.len(), 0);
8961
8962         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8963         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8964         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8965
8966         confirm_transaction_at(&nodes[1], &tx, 1);
8967         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8968         check_added_monitors!(nodes[1], 1);
8969         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8970         assert_eq!(events_2.len(), 1);
8971         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8972                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8973                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8974                         assert_eq!(msg.data, "funding tx had wrong script/value or output index");
8975                 } else { panic!(); }
8976         } else { panic!(); }
8977         assert_eq!(nodes[1].node.list_channels().len(), 0);
8978 }
8979
8980 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8981         // In the first version of the chain::Confirm interface, after a refactor was made to not
8982         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8983         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8984         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8985         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8986         // spending transaction until height N+1 (or greater). This was due to the way
8987         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8988         // spending transaction at the height the input transaction was confirmed at, not whether we
8989         // should broadcast a spending transaction at the current height.
8990         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8991         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8992         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
8993         // until we learned about an additional block.
8994         //
8995         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
8996         // aren't broadcasting transactions too early (ie not broadcasting them at all).
8997         let chanmon_cfgs = create_chanmon_cfgs(3);
8998         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8999         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9000         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9001         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9002
9003         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9004         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9005         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9006         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9007         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9008
9009         nodes[1].node.force_close_channel(&channel_id).unwrap();
9010         check_closed_broadcast!(nodes[1], true);
9011         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9012         check_added_monitors!(nodes[1], 1);
9013         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9014         assert_eq!(node_txn.len(), 1);
9015
9016         let conf_height = nodes[1].best_block_info().1;
9017         if !test_height_before_timelock {
9018                 connect_blocks(&nodes[1], 24 * 6);
9019         }
9020         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9021                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9022         if test_height_before_timelock {
9023                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9024                 // generate any events or broadcast any transactions
9025                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9026                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9027         } else {
9028                 // We should broadcast an HTLC transaction spending our funding transaction first
9029                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9030                 assert_eq!(spending_txn.len(), 2);
9031                 assert_eq!(spending_txn[0], node_txn[0]);
9032                 check_spends!(spending_txn[1], node_txn[0]);
9033                 // We should also generate a SpendableOutputs event with the to_self output (as its
9034                 // timelock is up).
9035                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9036                 assert_eq!(descriptor_spend_txn.len(), 1);
9037
9038                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9039                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9040                 // additional block built on top of the current chain.
9041                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9042                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9043                 expect_pending_htlcs_forwardable!(nodes[1]);
9044                 check_added_monitors!(nodes[1], 1);
9045
9046                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9047                 assert!(updates.update_add_htlcs.is_empty());
9048                 assert!(updates.update_fulfill_htlcs.is_empty());
9049                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9050                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9051                 assert!(updates.update_fee.is_none());
9052                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9053                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9054                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9055         }
9056 }
9057
9058 #[test]
9059 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9060         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9061         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9062 }
9063
9064 #[test]
9065 fn test_forwardable_regen() {
9066         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9067         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9068         // HTLCs.
9069         // We test it for both payment receipt and payment forwarding.
9070
9071         let chanmon_cfgs = create_chanmon_cfgs(3);
9072         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9073         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9074         let persister: test_utils::TestPersister;
9075         let new_chain_monitor: test_utils::TestChainMonitor;
9076         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9077         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9078         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9079         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9080
9081         // First send a payment to nodes[1]
9082         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9083         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9084         check_added_monitors!(nodes[0], 1);
9085
9086         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9087         assert_eq!(events.len(), 1);
9088         let payment_event = SendEvent::from_event(events.pop().unwrap());
9089         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9090         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9091
9092         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9093
9094         // Next send a payment which is forwarded by nodes[1]
9095         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9096         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9097         check_added_monitors!(nodes[0], 1);
9098
9099         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9100         assert_eq!(events.len(), 1);
9101         let payment_event = SendEvent::from_event(events.pop().unwrap());
9102         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9103         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9104
9105         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9106         // generated
9107         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9108
9109         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9110         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9111         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9112
9113         let nodes_1_serialized = nodes[1].node.encode();
9114         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9115         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9116         {
9117                 let monitors = nodes[1].chain_monitor.chain_monitor.monitors.read().unwrap();
9118                 let mut monitor_iter = monitors.iter();
9119                 monitor_iter.next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
9120                 monitor_iter.next().unwrap().1.write(&mut chan_1_monitor_serialized).unwrap();
9121         }
9122
9123         persister = test_utils::TestPersister::new();
9124         let keys_manager = &chanmon_cfgs[1].keys_manager;
9125         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);
9126         nodes[1].chain_monitor = &new_chain_monitor;
9127
9128         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9129         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9130                 &mut chan_0_monitor_read, keys_manager).unwrap();
9131         assert!(chan_0_monitor_read.is_empty());
9132         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9133         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9134                 &mut chan_1_monitor_read, keys_manager).unwrap();
9135         assert!(chan_1_monitor_read.is_empty());
9136
9137         let mut nodes_1_read = &nodes_1_serialized[..];
9138         let (_, nodes_1_deserialized_tmp) = {
9139                 let mut channel_monitors = HashMap::new();
9140                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9141                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9142                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9143                         default_config: UserConfig::default(),
9144                         keys_manager,
9145                         fee_estimator: node_cfgs[1].fee_estimator,
9146                         chain_monitor: nodes[1].chain_monitor,
9147                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9148                         logger: nodes[1].logger,
9149                         channel_monitors,
9150                 }).unwrap()
9151         };
9152         nodes_1_deserialized = nodes_1_deserialized_tmp;
9153         assert!(nodes_1_read.is_empty());
9154
9155         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9156         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9157         nodes[1].node = &nodes_1_deserialized;
9158         check_added_monitors!(nodes[1], 2);
9159
9160         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9161         // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9162         // the commitment state.
9163         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9164
9165         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9166
9167         expect_pending_htlcs_forwardable!(nodes[1]);
9168         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9169         check_added_monitors!(nodes[1], 1);
9170
9171         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9172         assert_eq!(events.len(), 1);
9173         let payment_event = SendEvent::from_event(events.pop().unwrap());
9174         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9175         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9176         expect_pending_htlcs_forwardable!(nodes[2]);
9177         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9178
9179         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9180         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9181 }
9182
9183 #[test]
9184 fn test_keysend_payments_to_public_node() {
9185         let chanmon_cfgs = create_chanmon_cfgs(2);
9186         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9187         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9188         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9189
9190         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9191         let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9192         let payer_pubkey = nodes[0].node.get_our_node_id();
9193         let payee_pubkey = nodes[1].node.get_our_node_id();
9194         let route = get_keysend_route(
9195                 &payer_pubkey, &network_graph, &payee_pubkey, None, &vec![], 10000, 40, nodes[0].logger
9196         ).unwrap();
9197
9198         let test_preimage = PaymentPreimage([42; 32]);
9199         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9200         check_added_monitors!(nodes[0], 1);
9201         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9202         assert_eq!(events.len(), 1);
9203         let event = events.pop().unwrap();
9204         let path = vec![&nodes[1]];
9205         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9206         claim_payment(&nodes[0], &path, test_preimage);
9207 }
9208
9209 #[test]
9210 fn test_keysend_payments_to_private_node() {
9211         let chanmon_cfgs = create_chanmon_cfgs(2);
9212         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9213         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9214         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9215
9216         let payer_pubkey = nodes[0].node.get_our_node_id();
9217         let payee_pubkey = nodes[1].node.get_our_node_id();
9218         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9219         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9220
9221         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9222         let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9223         let first_hops = nodes[0].node.list_usable_channels();
9224         let route = get_keysend_route(
9225                 &payer_pubkey, &network_graph, &payee_pubkey, Some(&first_hops.iter().collect::<Vec<_>>()),
9226                 &vec![], 10000, 40, nodes[0].logger
9227         ).unwrap();
9228
9229         let test_preimage = PaymentPreimage([42; 32]);
9230         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9231         check_added_monitors!(nodes[0], 1);
9232         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9233         assert_eq!(events.len(), 1);
9234         let event = events.pop().unwrap();
9235         let path = vec![&nodes[1]];
9236         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9237         claim_payment(&nodes[0], &path, test_preimage);
9238 }