]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/functional_tests.rs
Merge pull request #1098 from 1nF0rmed/2021-09-adds-discard-funding-event
[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::router::{Route, RouteHop, RouteHint, RouteHintHop, get_route, get_keysend_route};
27 use routing::network_graph::{NetworkUpdate, RoutingFees};
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         let logger = test_utils::TestLogger::new();
130
131         // balancing
132         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
133
134         // A                                        B
135         // update_fee                            ->
136         // send (1) commitment_signed            -.
137         //                                       <- update_add_htlc/commitment_signed
138         // send (2) RAA (awaiting remote revoke) -.
139         // (1) commitment_signed is delivered    ->
140         //                                       .- send (3) RAA (awaiting remote revoke)
141         // (2) RAA is delivered                  ->
142         //                                       .- send (4) commitment_signed
143         //                                       <- (3) RAA is delivered
144         // send (5) commitment_signed            -.
145         //                                       <- (4) commitment_signed is delivered
146         // send (6) RAA                          -.
147         // (5) commitment_signed is delivered    ->
148         //                                       <- RAA
149         // (6) RAA is delivered                  ->
150
151         // First nodes[0] generates an update_fee
152         {
153                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
154                 *feerate_lock += 20;
155         }
156         nodes[0].node.timer_tick_occurred();
157         check_added_monitors!(nodes[0], 1);
158
159         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
160         assert_eq!(events_0.len(), 1);
161         let (update_msg, commitment_signed) = match events_0[0] { // (1)
162                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
163                         (update_fee.as_ref(), commitment_signed)
164                 },
165                 _ => panic!("Unexpected event"),
166         };
167
168         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
169
170         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
171         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[0]);
172         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
173         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &Some(our_payment_secret)).unwrap();
174         check_added_monitors!(nodes[1], 1);
175
176         let payment_event = {
177                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
178                 assert_eq!(events_1.len(), 1);
179                 SendEvent::from_event(events_1.remove(0))
180         };
181         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
182         assert_eq!(payment_event.msgs.len(), 1);
183
184         // ...now when the messages get delivered everyone should be happy
185         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
186         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
187         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
188         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
189         check_added_monitors!(nodes[0], 1);
190
191         // deliver(1), generate (3):
192         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
193         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
194         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
195         check_added_monitors!(nodes[1], 1);
196
197         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
198         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
199         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
200         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
201         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
202         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
203         assert!(bs_update.update_fee.is_none()); // (4)
204         check_added_monitors!(nodes[1], 1);
205
206         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
207         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
208         assert!(as_update.update_add_htlcs.is_empty()); // (5)
209         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
210         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
211         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
212         assert!(as_update.update_fee.is_none()); // (5)
213         check_added_monitors!(nodes[0], 1);
214
215         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
216         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
217         // only (6) so get_event_msg's assert(len == 1) passes
218         check_added_monitors!(nodes[0], 1);
219
220         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
221         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
222         check_added_monitors!(nodes[1], 1);
223
224         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
225         check_added_monitors!(nodes[0], 1);
226
227         let events_2 = nodes[0].node.get_and_clear_pending_events();
228         assert_eq!(events_2.len(), 1);
229         match events_2[0] {
230                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
231                 _ => panic!("Unexpected event"),
232         }
233
234         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
235         check_added_monitors!(nodes[1], 1);
236 }
237
238 #[test]
239 fn test_update_fee_unordered_raa() {
240         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
241         // crash in an earlier version of the update_fee patch)
242         let chanmon_cfgs = create_chanmon_cfgs(2);
243         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
244         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
245         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
246         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
247         let logger = test_utils::TestLogger::new();
248
249         // balancing
250         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
251
252         // First nodes[0] generates an update_fee
253         {
254                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
255                 *feerate_lock += 20;
256         }
257         nodes[0].node.timer_tick_occurred();
258         check_added_monitors!(nodes[0], 1);
259
260         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
261         assert_eq!(events_0.len(), 1);
262         let update_msg = match events_0[0] { // (1)
263                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
264                         update_fee.as_ref()
265                 },
266                 _ => panic!("Unexpected event"),
267         };
268
269         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
270
271         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
272         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[0]);
273         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
274         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &Some(our_payment_secret)).unwrap();
275         check_added_monitors!(nodes[1], 1);
276
277         let payment_event = {
278                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
279                 assert_eq!(events_1.len(), 1);
280                 SendEvent::from_event(events_1.remove(0))
281         };
282         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
283         assert_eq!(payment_event.msgs.len(), 1);
284
285         // ...now when the messages get delivered everyone should be happy
286         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
287         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
288         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
289         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
290         check_added_monitors!(nodes[0], 1);
291
292         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
293         check_added_monitors!(nodes[1], 1);
294
295         // We can't continue, sadly, because our (1) now has a bogus signature
296 }
297
298 #[test]
299 fn test_multi_flight_update_fee() {
300         let chanmon_cfgs = create_chanmon_cfgs(2);
301         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
302         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
303         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
304         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
305
306         // A                                        B
307         // update_fee/commitment_signed          ->
308         //                                       .- send (1) RAA and (2) commitment_signed
309         // update_fee (never committed)          ->
310         // (3) update_fee                        ->
311         // We have to manually generate the above update_fee, it is allowed by the protocol but we
312         // don't track which updates correspond to which revoke_and_ack responses so we're in
313         // AwaitingRAA mode and will not generate the update_fee yet.
314         //                                       <- (1) RAA delivered
315         // (3) is generated and send (4) CS      -.
316         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
317         // know the per_commitment_point to use for it.
318         //                                       <- (2) commitment_signed delivered
319         // revoke_and_ack                        ->
320         //                                          B should send no response here
321         // (4) commitment_signed delivered       ->
322         //                                       <- RAA/commitment_signed delivered
323         // revoke_and_ack                        ->
324
325         // First nodes[0] generates an update_fee
326         let initial_feerate;
327         {
328                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
329                 initial_feerate = *feerate_lock;
330                 *feerate_lock = initial_feerate + 20;
331         }
332         nodes[0].node.timer_tick_occurred();
333         check_added_monitors!(nodes[0], 1);
334
335         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
336         assert_eq!(events_0.len(), 1);
337         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
338                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
339                         (update_fee.as_ref().unwrap(), commitment_signed)
340                 },
341                 _ => panic!("Unexpected event"),
342         };
343
344         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
345         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
346         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
347         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
348         check_added_monitors!(nodes[1], 1);
349
350         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
351         // transaction:
352         {
353                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
354                 *feerate_lock = initial_feerate + 40;
355         }
356         nodes[0].node.timer_tick_occurred();
357         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
358         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
359
360         // Create the (3) update_fee message that nodes[0] will generate before it does...
361         let mut update_msg_2 = msgs::UpdateFee {
362                 channel_id: update_msg_1.channel_id.clone(),
363                 feerate_per_kw: (initial_feerate + 30) as u32,
364         };
365
366         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
367
368         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
369         // Deliver (3)
370         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
371
372         // Deliver (1), generating (3) and (4)
373         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
374         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
375         check_added_monitors!(nodes[0], 1);
376         assert!(as_second_update.update_add_htlcs.is_empty());
377         assert!(as_second_update.update_fulfill_htlcs.is_empty());
378         assert!(as_second_update.update_fail_htlcs.is_empty());
379         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
380         // Check that the update_fee newly generated matches what we delivered:
381         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
382         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
383
384         // Deliver (2) commitment_signed
385         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
386         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
387         check_added_monitors!(nodes[0], 1);
388         // No commitment_signed so get_event_msg's assert(len == 1) passes
389
390         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
391         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
392         check_added_monitors!(nodes[1], 1);
393
394         // Delever (4)
395         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
396         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
397         check_added_monitors!(nodes[1], 1);
398
399         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
400         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
401         check_added_monitors!(nodes[0], 1);
402
403         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
404         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
405         // No commitment_signed so get_event_msg's assert(len == 1) passes
406         check_added_monitors!(nodes[0], 1);
407
408         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
409         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
410         check_added_monitors!(nodes[1], 1);
411 }
412
413 fn do_test_1_conf_open(connect_style: ConnectStyle) {
414         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
415         // tests that we properly send one in that case.
416         let mut alice_config = UserConfig::default();
417         alice_config.own_channel_config.minimum_depth = 1;
418         alice_config.channel_options.announced_channel = true;
419         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
420         let mut bob_config = UserConfig::default();
421         bob_config.own_channel_config.minimum_depth = 1;
422         bob_config.channel_options.announced_channel = true;
423         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
424         let chanmon_cfgs = create_chanmon_cfgs(2);
425         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
426         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
427         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
428         *nodes[0].connect_style.borrow_mut() = connect_style;
429
430         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
431         mine_transaction(&nodes[1], &tx);
432         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()));
433
434         mine_transaction(&nodes[0], &tx);
435         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
436         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
437
438         for node in nodes {
439                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
440                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
441                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
442         }
443 }
444 #[test]
445 fn test_1_conf_open() {
446         do_test_1_conf_open(ConnectStyle::BestBlockFirst);
447         do_test_1_conf_open(ConnectStyle::TransactionsFirst);
448         do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
449 }
450
451 fn do_test_sanity_on_in_flight_opens(steps: u8) {
452         // Previously, we had issues deserializing channels when we hadn't connected the first block
453         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
454         // serialization round-trips and simply do steps towards opening a channel and then drop the
455         // Node objects.
456
457         let chanmon_cfgs = create_chanmon_cfgs(2);
458         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
459         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
460         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
461
462         if steps & 0b1000_0000 != 0{
463                 let block = Block {
464                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
465                         txdata: vec![],
466                 };
467                 connect_block(&nodes[0], &block);
468                 connect_block(&nodes[1], &block);
469         }
470
471         if steps & 0x0f == 0 { return; }
472         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
473         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
474
475         if steps & 0x0f == 1 { return; }
476         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
477         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
478
479         if steps & 0x0f == 2 { return; }
480         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
481
482         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
483
484         if steps & 0x0f == 3 { return; }
485         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
486         check_added_monitors!(nodes[0], 0);
487         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
488
489         if steps & 0x0f == 4 { return; }
490         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
491         {
492                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
493                 assert_eq!(added_monitors.len(), 1);
494                 assert_eq!(added_monitors[0].0, funding_output);
495                 added_monitors.clear();
496         }
497         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
498
499         if steps & 0x0f == 5 { return; }
500         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
501         {
502                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
503                 assert_eq!(added_monitors.len(), 1);
504                 assert_eq!(added_monitors[0].0, funding_output);
505                 added_monitors.clear();
506         }
507
508         let events_4 = nodes[0].node.get_and_clear_pending_events();
509         assert_eq!(events_4.len(), 0);
510
511         if steps & 0x0f == 6 { return; }
512         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
513
514         if steps & 0x0f == 7 { return; }
515         confirm_transaction_at(&nodes[0], &tx, 2);
516         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
517         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
518 }
519
520 #[test]
521 fn test_sanity_on_in_flight_opens() {
522         do_test_sanity_on_in_flight_opens(0);
523         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
524         do_test_sanity_on_in_flight_opens(1);
525         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
526         do_test_sanity_on_in_flight_opens(2);
527         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
528         do_test_sanity_on_in_flight_opens(3);
529         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
530         do_test_sanity_on_in_flight_opens(4);
531         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
532         do_test_sanity_on_in_flight_opens(5);
533         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
534         do_test_sanity_on_in_flight_opens(6);
535         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
536         do_test_sanity_on_in_flight_opens(7);
537         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
538         do_test_sanity_on_in_flight_opens(8);
539         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
540 }
541
542 #[test]
543 fn test_update_fee_vanilla() {
544         let chanmon_cfgs = create_chanmon_cfgs(2);
545         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
546         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
547         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
548         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
549
550         {
551                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
552                 *feerate_lock += 25;
553         }
554         nodes[0].node.timer_tick_occurred();
555         check_added_monitors!(nodes[0], 1);
556
557         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
558         assert_eq!(events_0.len(), 1);
559         let (update_msg, commitment_signed) = match events_0[0] {
560                         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 } } => {
561                         (update_fee.as_ref(), commitment_signed)
562                 },
563                 _ => panic!("Unexpected event"),
564         };
565         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
566
567         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
568         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
569         check_added_monitors!(nodes[1], 1);
570
571         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
572         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
573         check_added_monitors!(nodes[0], 1);
574
575         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
576         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
577         // No commitment_signed so get_event_msg's assert(len == 1) passes
578         check_added_monitors!(nodes[0], 1);
579
580         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
581         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
582         check_added_monitors!(nodes[1], 1);
583 }
584
585 #[test]
586 fn test_update_fee_that_funder_cannot_afford() {
587         let chanmon_cfgs = create_chanmon_cfgs(2);
588         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
589         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
590         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
591         let channel_value = 1888;
592         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
593         let channel_id = chan.2;
594
595         let feerate = 260;
596         {
597                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
598                 *feerate_lock = feerate;
599         }
600         nodes[0].node.timer_tick_occurred();
601         check_added_monitors!(nodes[0], 1);
602         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
603
604         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
605
606         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
607
608         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
609         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
610         {
611                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
612
613                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
614                 let num_htlcs = commitment_tx.output.len() - 2;
615                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
616                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
617                 actual_fee = channel_value - actual_fee;
618                 assert_eq!(total_fee, actual_fee);
619         }
620
621         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
622         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
623         {
624                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
625                 *feerate_lock = feerate + 2;
626         }
627         nodes[0].node.timer_tick_occurred();
628         check_added_monitors!(nodes[0], 1);
629
630         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
631
632         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
633
634         //While producing the commitment_signed response after handling a received update_fee request the
635         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
636         //Should produce and error.
637         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
638         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
639         check_added_monitors!(nodes[1], 1);
640         check_closed_broadcast!(nodes[1], true);
641         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
642 }
643
644 #[test]
645 fn test_update_fee_with_fundee_update_add_htlc() {
646         let chanmon_cfgs = create_chanmon_cfgs(2);
647         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
648         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
649         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
650         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
651         let logger = test_utils::TestLogger::new();
652
653         // balancing
654         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
655
656         {
657                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
658                 *feerate_lock += 20;
659         }
660         nodes[0].node.timer_tick_occurred();
661         check_added_monitors!(nodes[0], 1);
662
663         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
664         assert_eq!(events_0.len(), 1);
665         let (update_msg, commitment_signed) = match events_0[0] {
666                         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 } } => {
667                         (update_fee.as_ref(), commitment_signed)
668                 },
669                 _ => panic!("Unexpected event"),
670         };
671         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
672         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
673         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
674         check_added_monitors!(nodes[1], 1);
675
676         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[0]);
677         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
678         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 800000, TEST_FINAL_CLTV, &logger).unwrap();
679
680         // nothing happens since node[1] is in AwaitingRemoteRevoke
681         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
682         {
683                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
684                 assert_eq!(added_monitors.len(), 0);
685                 added_monitors.clear();
686         }
687         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
688         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
689         // node[1] has nothing to do
690
691         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
692         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
693         check_added_monitors!(nodes[0], 1);
694
695         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
696         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
697         // No commitment_signed so get_event_msg's assert(len == 1) passes
698         check_added_monitors!(nodes[0], 1);
699         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
700         check_added_monitors!(nodes[1], 1);
701         // AwaitingRemoteRevoke ends here
702
703         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
704         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
705         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
706         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
707         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
708         assert_eq!(commitment_update.update_fee.is_none(), true);
709
710         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
711         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
712         check_added_monitors!(nodes[0], 1);
713         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
714
715         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
716         check_added_monitors!(nodes[1], 1);
717         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
718
719         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
720         check_added_monitors!(nodes[1], 1);
721         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
722         // No commitment_signed so get_event_msg's assert(len == 1) passes
723
724         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
725         check_added_monitors!(nodes[0], 1);
726         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
727
728         expect_pending_htlcs_forwardable!(nodes[0]);
729
730         let events = nodes[0].node.get_and_clear_pending_events();
731         assert_eq!(events.len(), 1);
732         match events[0] {
733                 Event::PaymentReceived { .. } => { },
734                 _ => panic!("Unexpected event"),
735         };
736
737         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
738
739         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
740         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
741         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
742         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
743         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
744 }
745
746 #[test]
747 fn test_update_fee() {
748         let chanmon_cfgs = create_chanmon_cfgs(2);
749         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
750         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
751         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
752         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
753         let channel_id = chan.2;
754
755         // A                                        B
756         // (1) update_fee/commitment_signed      ->
757         //                                       <- (2) revoke_and_ack
758         //                                       .- send (3) commitment_signed
759         // (4) update_fee/commitment_signed      ->
760         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
761         //                                       <- (3) commitment_signed delivered
762         // send (6) revoke_and_ack               -.
763         //                                       <- (5) deliver revoke_and_ack
764         // (6) deliver revoke_and_ack            ->
765         //                                       .- send (7) commitment_signed in response to (4)
766         //                                       <- (7) deliver commitment_signed
767         // revoke_and_ack                        ->
768
769         // Create and deliver (1)...
770         let feerate;
771         {
772                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
773                 feerate = *feerate_lock;
774                 *feerate_lock = feerate + 20;
775         }
776         nodes[0].node.timer_tick_occurred();
777         check_added_monitors!(nodes[0], 1);
778
779         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
780         assert_eq!(events_0.len(), 1);
781         let (update_msg, commitment_signed) = match events_0[0] {
782                         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 } } => {
783                         (update_fee.as_ref(), commitment_signed)
784                 },
785                 _ => panic!("Unexpected event"),
786         };
787         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
788
789         // Generate (2) and (3):
790         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
791         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
792         check_added_monitors!(nodes[1], 1);
793
794         // Deliver (2):
795         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
796         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
797         check_added_monitors!(nodes[0], 1);
798
799         // Create and deliver (4)...
800         {
801                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
802                 *feerate_lock = feerate + 30;
803         }
804         nodes[0].node.timer_tick_occurred();
805         check_added_monitors!(nodes[0], 1);
806         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
807         assert_eq!(events_0.len(), 1);
808         let (update_msg, commitment_signed) = match events_0[0] {
809                         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 } } => {
810                         (update_fee.as_ref(), commitment_signed)
811                 },
812                 _ => panic!("Unexpected event"),
813         };
814
815         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
816         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
817         check_added_monitors!(nodes[1], 1);
818         // ... creating (5)
819         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
820         // No commitment_signed so get_event_msg's assert(len == 1) passes
821
822         // Handle (3), creating (6):
823         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
824         check_added_monitors!(nodes[0], 1);
825         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
826         // No commitment_signed so get_event_msg's assert(len == 1) passes
827
828         // Deliver (5):
829         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
830         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
831         check_added_monitors!(nodes[0], 1);
832
833         // Deliver (6), creating (7):
834         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
835         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
836         assert!(commitment_update.update_add_htlcs.is_empty());
837         assert!(commitment_update.update_fulfill_htlcs.is_empty());
838         assert!(commitment_update.update_fail_htlcs.is_empty());
839         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
840         assert!(commitment_update.update_fee.is_none());
841         check_added_monitors!(nodes[1], 1);
842
843         // Deliver (7)
844         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
845         check_added_monitors!(nodes[0], 1);
846         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
847         // No commitment_signed so get_event_msg's assert(len == 1) passes
848
849         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
850         check_added_monitors!(nodes[1], 1);
851         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
852
853         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
854         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
855         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
856         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
857         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
858 }
859
860 #[test]
861 fn fake_network_test() {
862         // Simple test which builds a network of ChannelManagers, connects them to each other, and
863         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
864         let chanmon_cfgs = create_chanmon_cfgs(4);
865         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
866         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
867         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
868
869         // Create some initial channels
870         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
871         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
872         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
873
874         // Rebalance the network a bit by relaying one payment through all the channels...
875         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
876         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
877         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
878         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
879
880         // Send some more payments
881         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
882         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
883         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
884
885         // Test failure packets
886         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
887         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
888
889         // Add a new channel that skips 3
890         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
891
892         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
893         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
894         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
895         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
896         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
897         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
898         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
899
900         // Do some rebalance loop payments, simultaneously
901         let mut hops = Vec::with_capacity(3);
902         hops.push(RouteHop {
903                 pubkey: nodes[2].node.get_our_node_id(),
904                 node_features: NodeFeatures::empty(),
905                 short_channel_id: chan_2.0.contents.short_channel_id,
906                 channel_features: ChannelFeatures::empty(),
907                 fee_msat: 0,
908                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
909         });
910         hops.push(RouteHop {
911                 pubkey: nodes[3].node.get_our_node_id(),
912                 node_features: NodeFeatures::empty(),
913                 short_channel_id: chan_3.0.contents.short_channel_id,
914                 channel_features: ChannelFeatures::empty(),
915                 fee_msat: 0,
916                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
917         });
918         hops.push(RouteHop {
919                 pubkey: nodes[1].node.get_our_node_id(),
920                 node_features: NodeFeatures::known(),
921                 short_channel_id: chan_4.0.contents.short_channel_id,
922                 channel_features: ChannelFeatures::known(),
923                 fee_msat: 1000000,
924                 cltv_expiry_delta: TEST_FINAL_CLTV,
925         });
926         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;
927         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;
928         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
929
930         let mut hops = Vec::with_capacity(3);
931         hops.push(RouteHop {
932                 pubkey: nodes[3].node.get_our_node_id(),
933                 node_features: NodeFeatures::empty(),
934                 short_channel_id: chan_4.0.contents.short_channel_id,
935                 channel_features: ChannelFeatures::empty(),
936                 fee_msat: 0,
937                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
938         });
939         hops.push(RouteHop {
940                 pubkey: nodes[2].node.get_our_node_id(),
941                 node_features: NodeFeatures::empty(),
942                 short_channel_id: chan_3.0.contents.short_channel_id,
943                 channel_features: ChannelFeatures::empty(),
944                 fee_msat: 0,
945                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
946         });
947         hops.push(RouteHop {
948                 pubkey: nodes[1].node.get_our_node_id(),
949                 node_features: NodeFeatures::known(),
950                 short_channel_id: chan_2.0.contents.short_channel_id,
951                 channel_features: ChannelFeatures::known(),
952                 fee_msat: 1000000,
953                 cltv_expiry_delta: TEST_FINAL_CLTV,
954         });
955         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;
956         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;
957         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
958
959         // Claim the rebalances...
960         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
961         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
962
963         // Add a duplicate new channel from 2 to 4
964         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
965
966         // Send some payments across both channels
967         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
968         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
969         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
970
971
972         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
973         let events = nodes[0].node.get_and_clear_pending_msg_events();
974         assert_eq!(events.len(), 0);
975         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);
976
977         //TODO: Test that routes work again here as we've been notified that the channel is full
978
979         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
980         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
981         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
982
983         // Close down the channels...
984         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
985         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
986         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
987         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
988         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
989         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
990         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
991         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
992         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
993         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
994         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
995         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
996         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
997         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
998         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
999 }
1000
1001 #[test]
1002 fn holding_cell_htlc_counting() {
1003         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1004         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1005         // commitment dance rounds.
1006         let chanmon_cfgs = create_chanmon_cfgs(3);
1007         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1008         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1009         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1010         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1011         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1012         let logger = test_utils::TestLogger::new();
1013
1014         let mut payments = Vec::new();
1015         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1016                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
1017                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1018                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1019                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1020                 payments.push((payment_preimage, payment_hash));
1021         }
1022         check_added_monitors!(nodes[1], 1);
1023
1024         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1025         assert_eq!(events.len(), 1);
1026         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1027         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1028
1029         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1030         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1031         // another HTLC.
1032         let (_, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[2]);
1033         {
1034                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1035                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1036                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1037                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1038                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1039                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1040         }
1041
1042         // This should also be true if we try to forward a payment.
1043         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[2]);
1044         {
1045                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1046                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1047                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1048                 check_added_monitors!(nodes[0], 1);
1049         }
1050
1051         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1052         assert_eq!(events.len(), 1);
1053         let payment_event = SendEvent::from_event(events.pop().unwrap());
1054         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1055
1056         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1057         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1058         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1059         // fails), the second will process the resulting failure and fail the HTLC backward.
1060         expect_pending_htlcs_forwardable!(nodes[1]);
1061         expect_pending_htlcs_forwardable!(nodes[1]);
1062         check_added_monitors!(nodes[1], 1);
1063
1064         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1065         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1066         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1067
1068         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1069
1070         // Now forward all the pending HTLCs and claim them back
1071         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1072         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1073         check_added_monitors!(nodes[2], 1);
1074
1075         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1076         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1077         check_added_monitors!(nodes[1], 1);
1078         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1079
1080         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1081         check_added_monitors!(nodes[1], 1);
1082         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1083
1084         for ref update in as_updates.update_add_htlcs.iter() {
1085                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1086         }
1087         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1088         check_added_monitors!(nodes[2], 1);
1089         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1090         check_added_monitors!(nodes[2], 1);
1091         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1092
1093         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1094         check_added_monitors!(nodes[1], 1);
1095         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1096         check_added_monitors!(nodes[1], 1);
1097         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1098
1099         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1100         check_added_monitors!(nodes[2], 1);
1101
1102         expect_pending_htlcs_forwardable!(nodes[2]);
1103
1104         let events = nodes[2].node.get_and_clear_pending_events();
1105         assert_eq!(events.len(), payments.len());
1106         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1107                 match event {
1108                         &Event::PaymentReceived { ref payment_hash, .. } => {
1109                                 assert_eq!(*payment_hash, *hash);
1110                         },
1111                         _ => panic!("Unexpected event"),
1112                 };
1113         }
1114
1115         for (preimage, _) in payments.drain(..) {
1116                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1117         }
1118
1119         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1120 }
1121
1122 #[test]
1123 fn duplicate_htlc_test() {
1124         // Test that we accept duplicate payment_hash HTLCs across the network and that
1125         // claiming/failing them are all separate and don't affect each other
1126         let chanmon_cfgs = create_chanmon_cfgs(6);
1127         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1128         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1129         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1130
1131         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1132         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1133         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1134         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1135         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1136         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1137
1138         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1139
1140         *nodes[0].network_payment_count.borrow_mut() -= 1;
1141         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1142
1143         *nodes[0].network_payment_count.borrow_mut() -= 1;
1144         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1145
1146         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1147         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1148         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1149 }
1150
1151 #[test]
1152 fn test_duplicate_htlc_different_direction_onchain() {
1153         // Test that ChannelMonitor doesn't generate 2 preimage txn
1154         // when we have 2 HTLCs with same preimage that go across a node
1155         // in opposite directions, even with the same payment secret.
1156         let chanmon_cfgs = create_chanmon_cfgs(2);
1157         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1158         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1159         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1160
1161         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1162         let logger = test_utils::TestLogger::new();
1163
1164         // balancing
1165         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1166
1167         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1168
1169         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1170         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 800_000, TEST_FINAL_CLTV, &logger).unwrap();
1171         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, 0).unwrap();
1172         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1173
1174         // Provide preimage to node 0 by claiming payment
1175         nodes[0].node.claim_funds(payment_preimage);
1176         check_added_monitors!(nodes[0], 1);
1177
1178         // Broadcast node 1 commitment txn
1179         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1180
1181         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1182         let mut has_both_htlcs = 0; // check htlcs match ones committed
1183         for outp in remote_txn[0].output.iter() {
1184                 if outp.value == 800_000 / 1000 {
1185                         has_both_htlcs += 1;
1186                 } else if outp.value == 900_000 / 1000 {
1187                         has_both_htlcs += 1;
1188                 }
1189         }
1190         assert_eq!(has_both_htlcs, 2);
1191
1192         mine_transaction(&nodes[0], &remote_txn[0]);
1193         check_added_monitors!(nodes[0], 1);
1194         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1195         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1196
1197         // Check we only broadcast 1 timeout tx
1198         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1199         assert_eq!(claim_txn.len(), 8);
1200         assert_eq!(claim_txn[1], claim_txn[4]);
1201         assert_eq!(claim_txn[2], claim_txn[5]);
1202         check_spends!(claim_txn[1], chan_1.3);
1203         check_spends!(claim_txn[2], claim_txn[1]);
1204         check_spends!(claim_txn[7], claim_txn[1]);
1205
1206         assert_eq!(claim_txn[0].input.len(), 1);
1207         assert_eq!(claim_txn[3].input.len(), 1);
1208         assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1209
1210         assert_eq!(claim_txn[0].input.len(), 1);
1211         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1212         check_spends!(claim_txn[0], remote_txn[0]);
1213         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1214         assert_eq!(claim_txn[6].input.len(), 1);
1215         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1216         check_spends!(claim_txn[6], remote_txn[0]);
1217         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1218
1219         let events = nodes[0].node.get_and_clear_pending_msg_events();
1220         assert_eq!(events.len(), 3);
1221         for e in events {
1222                 match e {
1223                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1224                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1225                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1226                                 assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1227                         },
1228                         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, .. } } => {
1229                                 assert!(update_add_htlcs.is_empty());
1230                                 assert!(update_fail_htlcs.is_empty());
1231                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1232                                 assert!(update_fail_malformed_htlcs.is_empty());
1233                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1234                         },
1235                         _ => panic!("Unexpected event"),
1236                 }
1237         }
1238 }
1239
1240 #[test]
1241 fn test_basic_channel_reserve() {
1242         let chanmon_cfgs = create_chanmon_cfgs(2);
1243         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1244         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1245         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1246         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1247         let logger = test_utils::TestLogger::new();
1248
1249         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1250         let channel_reserve = chan_stat.channel_reserve_msat;
1251
1252         // The 2* and +1 are for the fee spike reserve.
1253         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
1254         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1255         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1256         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1257         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes.last().unwrap().node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), max_can_send + 1, TEST_FINAL_CLTV, &logger).unwrap();
1258         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1259         match err {
1260                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1261                         match &fails[0] {
1262                                 &APIError::ChannelUnavailable{ref err} =>
1263                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1264                                 _ => panic!("Unexpected error variant"),
1265                         }
1266                 },
1267                 _ => panic!("Unexpected error variant"),
1268         }
1269         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1270         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);
1271
1272         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1273 }
1274
1275 #[test]
1276 fn test_fee_spike_violation_fails_htlc() {
1277         let chanmon_cfgs = create_chanmon_cfgs(2);
1278         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1279         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1280         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1281         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1282
1283         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1284         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1285         let secp_ctx = Secp256k1::new();
1286         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1287
1288         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1289
1290         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1291         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1292         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1293         let msg = msgs::UpdateAddHTLC {
1294                 channel_id: chan.2,
1295                 htlc_id: 0,
1296                 amount_msat: htlc_msat,
1297                 payment_hash: payment_hash,
1298                 cltv_expiry: htlc_cltv,
1299                 onion_routing_packet: onion_packet,
1300         };
1301
1302         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1303
1304         // Now manually create the commitment_signed message corresponding to the update_add
1305         // nodes[0] just sent. In the code for construction of this message, "local" refers
1306         // to the sender of the message, and "remote" refers to the receiver.
1307
1308         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1309
1310         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1311
1312         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1313         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1314         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1315                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1316                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1317                 let chan_signer = local_chan.get_signer();
1318                 // Make the signer believe we validated another commitment, so we can release the secret
1319                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1320
1321                 let pubkeys = chan_signer.pubkeys();
1322                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1323                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1324                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1325                  chan_signer.pubkeys().funding_pubkey)
1326         };
1327         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1328                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1329                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1330                 let chan_signer = remote_chan.get_signer();
1331                 let pubkeys = chan_signer.pubkeys();
1332                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1333                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1334                  chan_signer.pubkeys().funding_pubkey)
1335         };
1336
1337         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1338         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1339                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1340
1341         // Build the remote commitment transaction so we can sign it, and then later use the
1342         // signature for the commitment_signed message.
1343         let local_chan_balance = 1313;
1344
1345         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1346                 offered: false,
1347                 amount_msat: 3460001,
1348                 cltv_expiry: htlc_cltv,
1349                 payment_hash,
1350                 transaction_output_index: Some(1),
1351         };
1352
1353         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1354
1355         let res = {
1356                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1357                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1358                 let local_chan_signer = local_chan.get_signer();
1359                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1360                         commitment_number,
1361                         95000,
1362                         local_chan_balance,
1363                         false, local_funding, remote_funding,
1364                         commit_tx_keys.clone(),
1365                         feerate_per_kw,
1366                         &mut vec![(accepted_htlc_info, ())],
1367                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1368                 );
1369                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1370         };
1371
1372         let commit_signed_msg = msgs::CommitmentSigned {
1373                 channel_id: chan.2,
1374                 signature: res.0,
1375                 htlc_signatures: res.1
1376         };
1377
1378         // Send the commitment_signed message to the nodes[1].
1379         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1380         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1381
1382         // Send the RAA to nodes[1].
1383         let raa_msg = msgs::RevokeAndACK {
1384                 channel_id: chan.2,
1385                 per_commitment_secret: local_secret,
1386                 next_per_commitment_point: next_local_point
1387         };
1388         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1389
1390         let events = nodes[1].node.get_and_clear_pending_msg_events();
1391         assert_eq!(events.len(), 1);
1392         // Make sure the HTLC failed in the way we expect.
1393         match events[0] {
1394                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1395                         assert_eq!(update_fail_htlcs.len(), 1);
1396                         update_fail_htlcs[0].clone()
1397                 },
1398                 _ => panic!("Unexpected event"),
1399         };
1400         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1401                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1402
1403         check_added_monitors!(nodes[1], 2);
1404 }
1405
1406 #[test]
1407 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1408         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1409         // Set the fee rate for the channel very high, to the point where the fundee
1410         // sending any above-dust amount would result in a channel reserve violation.
1411         // In this test we check that we would be prevented from sending an HTLC in
1412         // this situation.
1413         let feerate_per_kw = 253;
1414         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1415         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1416         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1417         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1418         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1419
1420         let mut push_amt = 100_000_000;
1421         push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
1422         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1423
1424         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1425
1426         // Sending exactly enough to hit the reserve amount should be accepted
1427         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1428
1429         // However one more HTLC should be significantly over the reserve amount and fail.
1430         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1431         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1432                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1433         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1434         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);
1435 }
1436
1437 #[test]
1438 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1439         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1440         // Set the fee rate for the channel very high, to the point where the funder
1441         // receiving 1 update_add_htlc would result in them closing the channel due
1442         // to channel reserve violation. This close could also happen if the fee went
1443         // up a more realistic amount, but many HTLCs were outstanding at the time of
1444         // the update_add_htlc.
1445         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1446         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1447         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1448         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1449         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1450         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1451
1452         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1453         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1454         let secp_ctx = Secp256k1::new();
1455         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1456         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1457         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1458         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &Some(payment_secret), cur_height, &None).unwrap();
1459         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1460         let msg = msgs::UpdateAddHTLC {
1461                 channel_id: chan.2,
1462                 htlc_id: 1,
1463                 amount_msat: htlc_msat + 1,
1464                 payment_hash: payment_hash,
1465                 cltv_expiry: htlc_cltv,
1466                 onion_routing_packet: onion_packet,
1467         };
1468
1469         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1470         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1471         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);
1472         assert_eq!(nodes[0].node.list_channels().len(), 0);
1473         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1474         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1475         check_added_monitors!(nodes[0], 1);
1476         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() });
1477 }
1478
1479 #[test]
1480 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1481         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1482         // calculating our commitment transaction fee (this was previously broken).
1483         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1484         let feerate_per_kw = 253;
1485         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1486         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1487
1488         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1489         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1490         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1491
1492         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1493         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1494         // transaction fee with 0 HTLCs (183 sats)).
1495         let mut push_amt = 100_000_000;
1496         push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT) / 1000 * 1000;
1497         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1498         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1499
1500         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1501                 + feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000 * 1000 - 1;
1502         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1503         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1504         // commitment transaction fee.
1505         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1506
1507         // One more than the dust amt should fail, however.
1508         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1509         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1510                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1511 }
1512
1513 #[test]
1514 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1515         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1516         // calculating our counterparty's commitment transaction fee (this was previously broken).
1517         let chanmon_cfgs = create_chanmon_cfgs(2);
1518         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1519         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1520         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1521         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1522
1523         let payment_amt = 46000; // Dust amount
1524         // In the previous code, these first four payments would succeed.
1525         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1526         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1527         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1528         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1529
1530         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1531         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1532         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1533         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1534         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1535         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1536
1537         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1538         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1539         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1540         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1541 }
1542
1543 #[test]
1544 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1545         let chanmon_cfgs = create_chanmon_cfgs(3);
1546         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1547         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1548         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1549         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1550         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1551
1552         let feemsat = 239;
1553         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1554         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1555         let feerate = get_feerate!(nodes[0], chan.2);
1556
1557         // Add a 2* and +1 for the fee spike reserve.
1558         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1559         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;
1560         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1561
1562         // Add a pending HTLC.
1563         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1564         let payment_event_1 = {
1565                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1566                 check_added_monitors!(nodes[0], 1);
1567
1568                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1569                 assert_eq!(events.len(), 1);
1570                 SendEvent::from_event(events.remove(0))
1571         };
1572         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1573
1574         // Attempt to trigger a channel reserve violation --> payment failure.
1575         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1576         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;
1577         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1578         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1579
1580         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1581         let secp_ctx = Secp256k1::new();
1582         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1583         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1584         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1585         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1586         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1587         let msg = msgs::UpdateAddHTLC {
1588                 channel_id: chan.2,
1589                 htlc_id: 1,
1590                 amount_msat: htlc_msat + 1,
1591                 payment_hash: our_payment_hash_1,
1592                 cltv_expiry: htlc_cltv,
1593                 onion_routing_packet: onion_packet,
1594         };
1595
1596         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1597         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1598         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1599         assert_eq!(nodes[1].node.list_channels().len(), 1);
1600         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1601         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1602         check_added_monitors!(nodes[1], 1);
1603         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1604 }
1605
1606 #[test]
1607 fn test_inbound_outbound_capacity_is_not_zero() {
1608         let chanmon_cfgs = create_chanmon_cfgs(2);
1609         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1610         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1611         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1612         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1613         let channels0 = node_chanmgrs[0].list_channels();
1614         let channels1 = node_chanmgrs[1].list_channels();
1615         assert_eq!(channels0.len(), 1);
1616         assert_eq!(channels1.len(), 1);
1617
1618         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1619         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1620         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1621
1622         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1623         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1624 }
1625
1626 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1627         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1628 }
1629
1630 #[test]
1631 fn test_channel_reserve_holding_cell_htlcs() {
1632         let chanmon_cfgs = create_chanmon_cfgs(3);
1633         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1634         // When this test was written, the default base fee floated based on the HTLC count.
1635         // It is now fixed, so we simply set the fee to the expected value here.
1636         let mut config = test_default_channel_config();
1637         config.channel_options.forwarding_fee_base_msat = 239;
1638         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1639         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1640         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1641         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1642
1643         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1644         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1645
1646         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1647         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1648
1649         macro_rules! expect_forward {
1650                 ($node: expr) => {{
1651                         let mut events = $node.node.get_and_clear_pending_msg_events();
1652                         assert_eq!(events.len(), 1);
1653                         check_added_monitors!($node, 1);
1654                         let payment_event = SendEvent::from_event(events.remove(0));
1655                         payment_event
1656                 }}
1657         }
1658
1659         let feemsat = 239; // set above
1660         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1661         let feerate = get_feerate!(nodes[0], chan_1.2);
1662
1663         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1664
1665         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1666         {
1667                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1668                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1669                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1670                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1671                         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)));
1672                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1673                 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);
1674         }
1675
1676         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1677         // nodes[0]'s wealth
1678         loop {
1679                 let amt_msat = recv_value_0 + total_fee_msat;
1680                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1681                 // Also, ensure that each payment has enough to be over the dust limit to
1682                 // ensure it'll be included in each commit tx fee calculation.
1683                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1684                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1685                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1686                         break;
1687                 }
1688                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1689
1690                 let (stat01_, stat11_, stat12_, stat22_) = (
1691                         get_channel_value_stat!(nodes[0], chan_1.2),
1692                         get_channel_value_stat!(nodes[1], chan_1.2),
1693                         get_channel_value_stat!(nodes[1], chan_2.2),
1694                         get_channel_value_stat!(nodes[2], chan_2.2),
1695                 );
1696
1697                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1698                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1699                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1700                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1701                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1702         }
1703
1704         // adding pending output.
1705         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1706         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1707         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1708         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1709         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1710         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1711         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1712         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1713         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1714         // policy.
1715         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1716         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1717         let amt_msat_1 = recv_value_1 + total_fee_msat;
1718
1719         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);
1720         let payment_event_1 = {
1721                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1722                 check_added_monitors!(nodes[0], 1);
1723
1724                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1725                 assert_eq!(events.len(), 1);
1726                 SendEvent::from_event(events.remove(0))
1727         };
1728         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1729
1730         // channel reserve test with htlc pending output > 0
1731         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1732         {
1733                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1734                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1735                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1736                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1737         }
1738
1739         // split the rest to test holding cell
1740         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1741         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1742         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1743         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1744         {
1745                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1746                 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);
1747         }
1748
1749         // now see if they go through on both sides
1750         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);
1751         // but this will stuck in the holding cell
1752         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1753         check_added_monitors!(nodes[0], 0);
1754         let events = nodes[0].node.get_and_clear_pending_events();
1755         assert_eq!(events.len(), 0);
1756
1757         // test with outbound holding cell amount > 0
1758         {
1759                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1760                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1761                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1762                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1763                 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);
1764         }
1765
1766         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);
1767         // this will also stuck in the holding cell
1768         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1769         check_added_monitors!(nodes[0], 0);
1770         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1771         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1772
1773         // flush the pending htlc
1774         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1775         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1776         check_added_monitors!(nodes[1], 1);
1777
1778         // the pending htlc should be promoted to committed
1779         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1780         check_added_monitors!(nodes[0], 1);
1781         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1782
1783         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1784         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1785         // No commitment_signed so get_event_msg's assert(len == 1) passes
1786         check_added_monitors!(nodes[0], 1);
1787
1788         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1789         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1790         check_added_monitors!(nodes[1], 1);
1791
1792         expect_pending_htlcs_forwardable!(nodes[1]);
1793
1794         let ref payment_event_11 = expect_forward!(nodes[1]);
1795         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1796         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1797
1798         expect_pending_htlcs_forwardable!(nodes[2]);
1799         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1800
1801         // flush the htlcs in the holding cell
1802         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1803         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1804         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1805         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1806         expect_pending_htlcs_forwardable!(nodes[1]);
1807
1808         let ref payment_event_3 = expect_forward!(nodes[1]);
1809         assert_eq!(payment_event_3.msgs.len(), 2);
1810         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1811         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1812
1813         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1814         expect_pending_htlcs_forwardable!(nodes[2]);
1815
1816         let events = nodes[2].node.get_and_clear_pending_events();
1817         assert_eq!(events.len(), 2);
1818         match events[0] {
1819                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1820                         assert_eq!(our_payment_hash_21, *payment_hash);
1821                         assert_eq!(recv_value_21, amt);
1822                         match &purpose {
1823                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1824                                         assert!(payment_preimage.is_none());
1825                                         assert_eq!(our_payment_secret_21, *payment_secret);
1826                                 },
1827                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1828                         }
1829                 },
1830                 _ => panic!("Unexpected event"),
1831         }
1832         match events[1] {
1833                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1834                         assert_eq!(our_payment_hash_22, *payment_hash);
1835                         assert_eq!(recv_value_22, amt);
1836                         match &purpose {
1837                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1838                                         assert!(payment_preimage.is_none());
1839                                         assert_eq!(our_payment_secret_22, *payment_secret);
1840                                 },
1841                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1842                         }
1843                 },
1844                 _ => panic!("Unexpected event"),
1845         }
1846
1847         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1848         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1849         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1850
1851         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
1852         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1853         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1854
1855         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
1856         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);
1857         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1858         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1859         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1860
1861         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1862         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1863 }
1864
1865 #[test]
1866 fn channel_reserve_in_flight_removes() {
1867         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1868         // can send to its counterparty, but due to update ordering, the other side may not yet have
1869         // considered those HTLCs fully removed.
1870         // This tests that we don't count HTLCs which will not be included in the next remote
1871         // commitment transaction towards the reserve value (as it implies no commitment transaction
1872         // will be generated which violates the remote reserve value).
1873         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1874         // To test this we:
1875         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1876         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1877         //    you only consider the value of the first HTLC, it may not),
1878         //  * start routing a third HTLC from A to B,
1879         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1880         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1881         //  * deliver the first fulfill from B
1882         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1883         //    claim,
1884         //  * deliver A's response CS and RAA.
1885         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1886         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
1887         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1888         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1889         let chanmon_cfgs = create_chanmon_cfgs(2);
1890         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1891         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1892         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1893         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1894         let logger = test_utils::TestLogger::new();
1895
1896         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1897         // Route the first two HTLCs.
1898         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1899         let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1900
1901         // Start routing the third HTLC (this is just used to get everyone in the right state).
1902         let (payment_preimage_3, payment_hash_3, payment_secret_3) = get_payment_preimage_hash!(nodes[1]);
1903         let send_1 = {
1904                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1905                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
1906                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
1907                 check_added_monitors!(nodes[0], 1);
1908                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1909                 assert_eq!(events.len(), 1);
1910                 SendEvent::from_event(events.remove(0))
1911         };
1912
1913         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1914         // initial fulfill/CS.
1915         assert!(nodes[1].node.claim_funds(payment_preimage_1));
1916         check_added_monitors!(nodes[1], 1);
1917         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1918
1919         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1920         // remove the second HTLC when we send the HTLC back from B to A.
1921         assert!(nodes[1].node.claim_funds(payment_preimage_2));
1922         check_added_monitors!(nodes[1], 1);
1923         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1924
1925         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1926         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1927         check_added_monitors!(nodes[0], 1);
1928         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1929         expect_payment_sent!(nodes[0], payment_preimage_1);
1930
1931         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1932         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1933         check_added_monitors!(nodes[1], 1);
1934         // B is already AwaitingRAA, so cant generate a CS here
1935         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1936
1937         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1938         check_added_monitors!(nodes[1], 1);
1939         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1940
1941         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1942         check_added_monitors!(nodes[0], 1);
1943         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1944
1945         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1946         check_added_monitors!(nodes[1], 1);
1947         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1948
1949         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1950         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1951         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1952         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1953         // on-chain as necessary).
1954         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1955         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1956         check_added_monitors!(nodes[0], 1);
1957         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1958         expect_payment_sent!(nodes[0], payment_preimage_2);
1959
1960         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1961         check_added_monitors!(nodes[1], 1);
1962         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1963
1964         expect_pending_htlcs_forwardable!(nodes[1]);
1965         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
1966
1967         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1968         // resolve the second HTLC from A's point of view.
1969         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1970         check_added_monitors!(nodes[0], 1);
1971         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1972
1973         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1974         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1975         let (payment_preimage_4, payment_hash_4, payment_secret_4) = get_payment_preimage_hash!(nodes[0]);
1976         let send_2 = {
1977                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1978                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 10000, TEST_FINAL_CLTV, &logger).unwrap();
1979                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
1980                 check_added_monitors!(nodes[1], 1);
1981                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1982                 assert_eq!(events.len(), 1);
1983                 SendEvent::from_event(events.remove(0))
1984         };
1985
1986         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1987         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1988         check_added_monitors!(nodes[0], 1);
1989         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1990
1991         // Now just resolve all the outstanding messages/HTLCs for completeness...
1992
1993         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1994         check_added_monitors!(nodes[1], 1);
1995         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1996
1997         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1998         check_added_monitors!(nodes[1], 1);
1999
2000         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2001         check_added_monitors!(nodes[0], 1);
2002         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2003
2004         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2005         check_added_monitors!(nodes[1], 1);
2006         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2007
2008         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2009         check_added_monitors!(nodes[0], 1);
2010
2011         expect_pending_htlcs_forwardable!(nodes[0]);
2012         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2013
2014         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2015         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2016 }
2017
2018 #[test]
2019 fn channel_monitor_network_test() {
2020         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2021         // tests that ChannelMonitor is able to recover from various states.
2022         let chanmon_cfgs = create_chanmon_cfgs(5);
2023         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2024         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2025         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2026
2027         // Create some initial channels
2028         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2029         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2030         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2031         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2032
2033         // Make sure all nodes are at the same starting height
2034         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2035         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2036         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2037         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2038         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2039
2040         // Rebalance the network a bit by relaying one payment through all the channels...
2041         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2042         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2043         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2044         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2045
2046         // Simple case with no pending HTLCs:
2047         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2048         check_added_monitors!(nodes[1], 1);
2049         check_closed_broadcast!(nodes[1], false);
2050         {
2051                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2052                 assert_eq!(node_txn.len(), 1);
2053                 mine_transaction(&nodes[0], &node_txn[0]);
2054                 check_added_monitors!(nodes[0], 1);
2055                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2056         }
2057         check_closed_broadcast!(nodes[0], true);
2058         assert_eq!(nodes[0].node.list_channels().len(), 0);
2059         assert_eq!(nodes[1].node.list_channels().len(), 1);
2060         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2061         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2062
2063         // One pending HTLC is discarded by the force-close:
2064         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2065
2066         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2067         // broadcasted until we reach the timelock time).
2068         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2069         check_closed_broadcast!(nodes[1], false);
2070         check_added_monitors!(nodes[1], 1);
2071         {
2072                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2073                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2074                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2075                 mine_transaction(&nodes[2], &node_txn[0]);
2076                 check_added_monitors!(nodes[2], 1);
2077                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2078         }
2079         check_closed_broadcast!(nodes[2], true);
2080         assert_eq!(nodes[1].node.list_channels().len(), 0);
2081         assert_eq!(nodes[2].node.list_channels().len(), 1);
2082         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2083         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2084
2085         macro_rules! claim_funds {
2086                 ($node: expr, $prev_node: expr, $preimage: expr) => {
2087                         {
2088                                 assert!($node.node.claim_funds($preimage));
2089                                 check_added_monitors!($node, 1);
2090
2091                                 let events = $node.node.get_and_clear_pending_msg_events();
2092                                 assert_eq!(events.len(), 1);
2093                                 match events[0] {
2094                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2095                                                 assert!(update_add_htlcs.is_empty());
2096                                                 assert!(update_fail_htlcs.is_empty());
2097                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2098                                         },
2099                                         _ => panic!("Unexpected event"),
2100                                 };
2101                         }
2102                 }
2103         }
2104
2105         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2106         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2107         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2108         check_added_monitors!(nodes[2], 1);
2109         check_closed_broadcast!(nodes[2], false);
2110         let node2_commitment_txid;
2111         {
2112                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2113                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2114                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2115                 node2_commitment_txid = node_txn[0].txid();
2116
2117                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2118                 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2119                 mine_transaction(&nodes[3], &node_txn[0]);
2120                 check_added_monitors!(nodes[3], 1);
2121                 check_preimage_claim(&nodes[3], &node_txn);
2122         }
2123         check_closed_broadcast!(nodes[3], true);
2124         assert_eq!(nodes[2].node.list_channels().len(), 0);
2125         assert_eq!(nodes[3].node.list_channels().len(), 1);
2126         check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2127         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2128
2129         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2130         // confusing us in the following tests.
2131         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2132
2133         // One pending HTLC to time out:
2134         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2135         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2136         // buffer space).
2137
2138         let (close_chan_update_1, close_chan_update_2) = {
2139                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2140                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2141                 assert_eq!(events.len(), 2);
2142                 let close_chan_update_1 = match events[0] {
2143                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2144                                 msg.clone()
2145                         },
2146                         _ => panic!("Unexpected event"),
2147                 };
2148                 match events[1] {
2149                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2150                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2151                         },
2152                         _ => panic!("Unexpected event"),
2153                 }
2154                 check_added_monitors!(nodes[3], 1);
2155
2156                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2157                 {
2158                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2159                         node_txn.retain(|tx| {
2160                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2161                                         false
2162                                 } else { true }
2163                         });
2164                 }
2165
2166                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2167
2168                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2169                 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2170
2171                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2172                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2173                 assert_eq!(events.len(), 2);
2174                 let close_chan_update_2 = match events[0] {
2175                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2176                                 msg.clone()
2177                         },
2178                         _ => panic!("Unexpected event"),
2179                 };
2180                 match events[1] {
2181                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2182                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2183                         },
2184                         _ => panic!("Unexpected event"),
2185                 }
2186                 check_added_monitors!(nodes[4], 1);
2187                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2188
2189                 mine_transaction(&nodes[4], &node_txn[0]);
2190                 check_preimage_claim(&nodes[4], &node_txn);
2191                 (close_chan_update_1, close_chan_update_2)
2192         };
2193         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2194         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2195         assert_eq!(nodes[3].node.list_channels().len(), 0);
2196         assert_eq!(nodes[4].node.list_channels().len(), 0);
2197
2198         nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2199         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2200         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2201 }
2202
2203 #[test]
2204 fn test_justice_tx() {
2205         // Test justice txn built on revoked HTLC-Success tx, against both sides
2206         let mut alice_config = UserConfig::default();
2207         alice_config.channel_options.announced_channel = true;
2208         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2209         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2210         let mut bob_config = UserConfig::default();
2211         bob_config.channel_options.announced_channel = true;
2212         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2213         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2214         let user_cfgs = [Some(alice_config), Some(bob_config)];
2215         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2216         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2217         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2218         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2219         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2220         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2221         // Create some new channels:
2222         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2223
2224         // A pending HTLC which will be revoked:
2225         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2226         // Get the will-be-revoked local txn from nodes[0]
2227         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2228         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2229         assert_eq!(revoked_local_txn[0].input.len(), 1);
2230         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2231         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2232         assert_eq!(revoked_local_txn[1].input.len(), 1);
2233         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2234         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2235         // Revoke the old state
2236         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2237
2238         {
2239                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2240                 {
2241                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2242                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2243                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2244
2245                         check_spends!(node_txn[0], revoked_local_txn[0]);
2246                         node_txn.swap_remove(0);
2247                         node_txn.truncate(1);
2248                 }
2249                 check_added_monitors!(nodes[1], 1);
2250                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2251                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2252
2253                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2254                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2255                 // Verify broadcast of revoked HTLC-timeout
2256                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2257                 check_added_monitors!(nodes[0], 1);
2258                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2259                 // Broadcast revoked HTLC-timeout on node 1
2260                 mine_transaction(&nodes[1], &node_txn[1]);
2261                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2262         }
2263         get_announce_close_broadcast_events(&nodes, 0, 1);
2264
2265         assert_eq!(nodes[0].node.list_channels().len(), 0);
2266         assert_eq!(nodes[1].node.list_channels().len(), 0);
2267
2268         // We test justice_tx build by A on B's revoked HTLC-Success tx
2269         // Create some new channels:
2270         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2271         {
2272                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2273                 node_txn.clear();
2274         }
2275
2276         // A pending HTLC which will be revoked:
2277         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2278         // Get the will-be-revoked local txn from B
2279         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2280         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2281         assert_eq!(revoked_local_txn[0].input.len(), 1);
2282         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2283         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2284         // Revoke the old state
2285         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2286         {
2287                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2288                 {
2289                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2290                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2291                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2292
2293                         check_spends!(node_txn[0], revoked_local_txn[0]);
2294                         node_txn.swap_remove(0);
2295                 }
2296                 check_added_monitors!(nodes[0], 1);
2297                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2298
2299                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2300                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2301                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2302                 check_added_monitors!(nodes[1], 1);
2303                 mine_transaction(&nodes[0], &node_txn[1]);
2304                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2305                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2306         }
2307         get_announce_close_broadcast_events(&nodes, 0, 1);
2308         assert_eq!(nodes[0].node.list_channels().len(), 0);
2309         assert_eq!(nodes[1].node.list_channels().len(), 0);
2310 }
2311
2312 #[test]
2313 fn revoked_output_claim() {
2314         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2315         // transaction is broadcast by its counterparty
2316         let chanmon_cfgs = create_chanmon_cfgs(2);
2317         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2318         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2319         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2320         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2321         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2322         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2323         assert_eq!(revoked_local_txn.len(), 1);
2324         // Only output is the full channel value back to nodes[0]:
2325         assert_eq!(revoked_local_txn[0].output.len(), 1);
2326         // Send a payment through, updating everyone's latest commitment txn
2327         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2328
2329         // Inform nodes[1] that nodes[0] broadcast a stale tx
2330         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2331         check_added_monitors!(nodes[1], 1);
2332         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2333         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2334         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2335
2336         check_spends!(node_txn[0], revoked_local_txn[0]);
2337         check_spends!(node_txn[1], chan_1.3);
2338
2339         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2340         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2341         get_announce_close_broadcast_events(&nodes, 0, 1);
2342         check_added_monitors!(nodes[0], 1);
2343         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2344 }
2345
2346 #[test]
2347 fn claim_htlc_outputs_shared_tx() {
2348         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2349         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2350         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2351         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2352         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2353         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2354
2355         // Create some new channel:
2356         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2357
2358         // Rebalance the network to generate htlc in the two directions
2359         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2360         // 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
2361         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2362         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2363
2364         // Get the will-be-revoked local txn from node[0]
2365         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2366         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2367         assert_eq!(revoked_local_txn[0].input.len(), 1);
2368         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2369         assert_eq!(revoked_local_txn[1].input.len(), 1);
2370         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2371         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2372         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2373
2374         //Revoke the old state
2375         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2376
2377         {
2378                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2379                 check_added_monitors!(nodes[0], 1);
2380                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2381                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2382                 check_added_monitors!(nodes[1], 1);
2383                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2384                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2385                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2386
2387                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2388                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2389
2390                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2391                 check_spends!(node_txn[0], revoked_local_txn[0]);
2392
2393                 let mut witness_lens = BTreeSet::new();
2394                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2395                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2396                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2397                 assert_eq!(witness_lens.len(), 3);
2398                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2399                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2400                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2401
2402                 // Next nodes[1] broadcasts its current local tx state:
2403                 assert_eq!(node_txn[1].input.len(), 1);
2404                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2405         }
2406         get_announce_close_broadcast_events(&nodes, 0, 1);
2407         assert_eq!(nodes[0].node.list_channels().len(), 0);
2408         assert_eq!(nodes[1].node.list_channels().len(), 0);
2409 }
2410
2411 #[test]
2412 fn claim_htlc_outputs_single_tx() {
2413         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2414         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2415         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2416         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2417         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2418         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2419
2420         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2421
2422         // Rebalance the network to generate htlc in the two directions
2423         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2424         // 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
2425         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2426         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2427         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2428
2429         // Get the will-be-revoked local txn from node[0]
2430         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2431
2432         //Revoke the old state
2433         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2434
2435         {
2436                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2437                 check_added_monitors!(nodes[0], 1);
2438                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2439                 check_added_monitors!(nodes[1], 1);
2440                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2441                 let mut events = nodes[0].node.get_and_clear_pending_events();
2442                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2443                 match events[1] {
2444                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2445                         _ => panic!("Unexpected event"),
2446                 }
2447
2448                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2449                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2450
2451                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2452                 assert_eq!(node_txn.len(), 9);
2453                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2454                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2455                 // 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)
2456                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2457
2458                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2459                 assert_eq!(node_txn[0].input.len(), 1);
2460                 check_spends!(node_txn[0], chan_1.3);
2461                 assert_eq!(node_txn[1].input.len(), 1);
2462                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2463                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2464                 check_spends!(node_txn[1], node_txn[0]);
2465
2466                 // Justice transactions are indices 1-2-4
2467                 assert_eq!(node_txn[2].input.len(), 1);
2468                 assert_eq!(node_txn[3].input.len(), 1);
2469                 assert_eq!(node_txn[4].input.len(), 1);
2470
2471                 check_spends!(node_txn[2], revoked_local_txn[0]);
2472                 check_spends!(node_txn[3], revoked_local_txn[0]);
2473                 check_spends!(node_txn[4], revoked_local_txn[0]);
2474
2475                 let mut witness_lens = BTreeSet::new();
2476                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2477                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2478                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2479                 assert_eq!(witness_lens.len(), 3);
2480                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2481                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2482                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2483         }
2484         get_announce_close_broadcast_events(&nodes, 0, 1);
2485         assert_eq!(nodes[0].node.list_channels().len(), 0);
2486         assert_eq!(nodes[1].node.list_channels().len(), 0);
2487 }
2488
2489 #[test]
2490 fn test_htlc_on_chain_success() {
2491         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2492         // the preimage backward accordingly. So here we test that ChannelManager is
2493         // broadcasting the right event to other nodes in payment path.
2494         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2495         // A --------------------> B ----------------------> C (preimage)
2496         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2497         // commitment transaction was broadcast.
2498         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2499         // towards B.
2500         // B should be able to claim via preimage if A then broadcasts its local tx.
2501         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2502         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2503         // PaymentSent event).
2504
2505         let chanmon_cfgs = create_chanmon_cfgs(3);
2506         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2507         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2508         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2509
2510         // Create some initial channels
2511         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2512         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2513
2514         // Ensure all nodes are at the same height
2515         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2516         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2517         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2518         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2519
2520         // Rebalance the network a bit by relaying one payment through all the channels...
2521         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2522         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2523
2524         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2525         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2526
2527         // Broadcast legit commitment tx from C on B's chain
2528         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2529         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2530         assert_eq!(commitment_tx.len(), 1);
2531         check_spends!(commitment_tx[0], chan_2.3);
2532         nodes[2].node.claim_funds(our_payment_preimage);
2533         nodes[2].node.claim_funds(our_payment_preimage_2);
2534         check_added_monitors!(nodes[2], 2);
2535         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2536         assert!(updates.update_add_htlcs.is_empty());
2537         assert!(updates.update_fail_htlcs.is_empty());
2538         assert!(updates.update_fail_malformed_htlcs.is_empty());
2539         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2540
2541         mine_transaction(&nodes[2], &commitment_tx[0]);
2542         check_closed_broadcast!(nodes[2], true);
2543         check_added_monitors!(nodes[2], 1);
2544         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2545         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)
2546         assert_eq!(node_txn.len(), 5);
2547         assert_eq!(node_txn[0], node_txn[3]);
2548         assert_eq!(node_txn[1], node_txn[4]);
2549         assert_eq!(node_txn[2], commitment_tx[0]);
2550         check_spends!(node_txn[0], commitment_tx[0]);
2551         check_spends!(node_txn[1], commitment_tx[0]);
2552         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2553         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2554         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2555         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2556         assert_eq!(node_txn[0].lock_time, 0);
2557         assert_eq!(node_txn[1].lock_time, 0);
2558
2559         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2560         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2561         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2562         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2563         {
2564                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2565                 assert_eq!(added_monitors.len(), 1);
2566                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2567                 added_monitors.clear();
2568         }
2569         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2570         assert_eq!(forwarded_events.len(), 3);
2571         match forwarded_events[0] {
2572                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2573                 _ => panic!("Unexpected event"),
2574         }
2575         if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2576                 } else { panic!(); }
2577         if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[2] {
2578                 } else { panic!(); }
2579         let events = nodes[1].node.get_and_clear_pending_msg_events();
2580         {
2581                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2582                 assert_eq!(added_monitors.len(), 2);
2583                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2584                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2585                 added_monitors.clear();
2586         }
2587         assert_eq!(events.len(), 3);
2588         match events[0] {
2589                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2590                 _ => panic!("Unexpected event"),
2591         }
2592         match events[1] {
2593                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2594                 _ => panic!("Unexpected event"),
2595         }
2596
2597         match events[2] {
2598                 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, .. } } => {
2599                         assert!(update_add_htlcs.is_empty());
2600                         assert!(update_fail_htlcs.is_empty());
2601                         assert_eq!(update_fulfill_htlcs.len(), 1);
2602                         assert!(update_fail_malformed_htlcs.is_empty());
2603                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2604                 },
2605                 _ => panic!("Unexpected event"),
2606         };
2607         macro_rules! check_tx_local_broadcast {
2608                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2609                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2610                         assert_eq!(node_txn.len(), 3);
2611                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2612                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2613                         check_spends!(node_txn[1], $commitment_tx);
2614                         check_spends!(node_txn[2], $commitment_tx);
2615                         assert_ne!(node_txn[1].lock_time, 0);
2616                         assert_ne!(node_txn[2].lock_time, 0);
2617                         if $htlc_offered {
2618                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2619                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2620                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2621                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2622                         } else {
2623                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2624                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2625                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2626                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2627                         }
2628                         check_spends!(node_txn[0], $chan_tx);
2629                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2630                         node_txn.clear();
2631                 } }
2632         }
2633         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2634         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2635         // timeout-claim of the output that nodes[2] just claimed via success.
2636         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2637
2638         // Broadcast legit commitment tx from A on B's chain
2639         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2640         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2641         check_spends!(node_a_commitment_tx[0], chan_1.3);
2642         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2643         check_closed_broadcast!(nodes[1], true);
2644         check_added_monitors!(nodes[1], 1);
2645         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2646         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2647         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2648         let commitment_spend =
2649                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2650                         check_spends!(node_txn[1], commitment_tx[0]);
2651                         check_spends!(node_txn[2], commitment_tx[0]);
2652                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2653                         &node_txn[0]
2654                 } else {
2655                         check_spends!(node_txn[0], commitment_tx[0]);
2656                         check_spends!(node_txn[1], commitment_tx[0]);
2657                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2658                         &node_txn[2]
2659                 };
2660
2661         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2662         assert_eq!(commitment_spend.input.len(), 2);
2663         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2664         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2665         assert_eq!(commitment_spend.lock_time, 0);
2666         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2667         check_spends!(node_txn[3], chan_1.3);
2668         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2669         check_spends!(node_txn[4], node_txn[3]);
2670         check_spends!(node_txn[5], node_txn[3]);
2671         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2672         // we already checked the same situation with A.
2673
2674         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2675         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2676         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2677         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2678         check_closed_broadcast!(nodes[0], true);
2679         check_added_monitors!(nodes[0], 1);
2680         let events = nodes[0].node.get_and_clear_pending_events();
2681         assert_eq!(events.len(), 3);
2682         let mut first_claimed = false;
2683         for event in events {
2684                 match event {
2685                         Event::PaymentSent { payment_preimage, payment_hash } => {
2686                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2687                                         assert!(!first_claimed);
2688                                         first_claimed = true;
2689                                 } else {
2690                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2691                                         assert_eq!(payment_hash, payment_hash_2);
2692                                 }
2693                         },
2694                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2695                         _ => panic!("Unexpected event"),
2696                 }
2697         }
2698         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2699 }
2700
2701 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2702         // Test that in case of a unilateral close onchain, we detect the state of output and
2703         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2704         // broadcasting the right event to other nodes in payment path.
2705         // A ------------------> B ----------------------> C (timeout)
2706         //    B's commitment tx                 C's commitment tx
2707         //            \                                  \
2708         //         B's HTLC timeout tx               B's timeout tx
2709
2710         let chanmon_cfgs = create_chanmon_cfgs(3);
2711         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2712         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2713         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2714         *nodes[0].connect_style.borrow_mut() = connect_style;
2715         *nodes[1].connect_style.borrow_mut() = connect_style;
2716         *nodes[2].connect_style.borrow_mut() = connect_style;
2717
2718         // Create some intial channels
2719         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2720         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2721
2722         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2723         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2724         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2725
2726         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2727
2728         // Broadcast legit commitment tx from C on B's chain
2729         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2730         check_spends!(commitment_tx[0], chan_2.3);
2731         nodes[2].node.fail_htlc_backwards(&payment_hash);
2732         check_added_monitors!(nodes[2], 0);
2733         expect_pending_htlcs_forwardable!(nodes[2]);
2734         check_added_monitors!(nodes[2], 1);
2735
2736         let events = nodes[2].node.get_and_clear_pending_msg_events();
2737         assert_eq!(events.len(), 1);
2738         match events[0] {
2739                 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, .. } } => {
2740                         assert!(update_add_htlcs.is_empty());
2741                         assert!(!update_fail_htlcs.is_empty());
2742                         assert!(update_fulfill_htlcs.is_empty());
2743                         assert!(update_fail_malformed_htlcs.is_empty());
2744                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2745                 },
2746                 _ => panic!("Unexpected event"),
2747         };
2748         mine_transaction(&nodes[2], &commitment_tx[0]);
2749         check_closed_broadcast!(nodes[2], true);
2750         check_added_monitors!(nodes[2], 1);
2751         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2752         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2753         assert_eq!(node_txn.len(), 1);
2754         check_spends!(node_txn[0], chan_2.3);
2755         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2756
2757         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2758         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2759         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2760         mine_transaction(&nodes[1], &commitment_tx[0]);
2761         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2762         let timeout_tx;
2763         {
2764                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2765                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2766                 assert_eq!(node_txn[0], node_txn[3]);
2767                 assert_eq!(node_txn[1], node_txn[4]);
2768
2769                 check_spends!(node_txn[2], commitment_tx[0]);
2770                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2771
2772                 check_spends!(node_txn[0], chan_2.3);
2773                 check_spends!(node_txn[1], node_txn[0]);
2774                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2775                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2776
2777                 timeout_tx = node_txn[2].clone();
2778                 node_txn.clear();
2779         }
2780
2781         mine_transaction(&nodes[1], &timeout_tx);
2782         check_added_monitors!(nodes[1], 1);
2783         check_closed_broadcast!(nodes[1], true);
2784         {
2785                 // B will rebroadcast a fee-bumped timeout transaction here.
2786                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2787                 assert_eq!(node_txn.len(), 1);
2788                 check_spends!(node_txn[0], commitment_tx[0]);
2789         }
2790
2791         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2792         {
2793                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2794                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2795                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2796                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2797                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2798                 if node_txn.len() == 1 {
2799                         check_spends!(node_txn[0], chan_2.3);
2800                 } else {
2801                         assert_eq!(node_txn.len(), 0);
2802                 }
2803         }
2804
2805         expect_pending_htlcs_forwardable!(nodes[1]);
2806         check_added_monitors!(nodes[1], 1);
2807         let events = nodes[1].node.get_and_clear_pending_msg_events();
2808         assert_eq!(events.len(), 1);
2809         match events[0] {
2810                 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, .. } } => {
2811                         assert!(update_add_htlcs.is_empty());
2812                         assert!(!update_fail_htlcs.is_empty());
2813                         assert!(update_fulfill_htlcs.is_empty());
2814                         assert!(update_fail_malformed_htlcs.is_empty());
2815                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2816                 },
2817                 _ => panic!("Unexpected event"),
2818         };
2819
2820         // Broadcast legit commitment tx from B on A's chain
2821         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2822         check_spends!(commitment_tx[0], chan_1.3);
2823
2824         mine_transaction(&nodes[0], &commitment_tx[0]);
2825         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2826
2827         check_closed_broadcast!(nodes[0], true);
2828         check_added_monitors!(nodes[0], 1);
2829         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2830         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2831         assert_eq!(node_txn.len(), 2);
2832         check_spends!(node_txn[0], chan_1.3);
2833         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2834         check_spends!(node_txn[1], commitment_tx[0]);
2835         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2836 }
2837
2838 #[test]
2839 fn test_htlc_on_chain_timeout() {
2840         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2841         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2842         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2843 }
2844
2845 #[test]
2846 fn test_simple_commitment_revoked_fail_backward() {
2847         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2848         // and fail backward accordingly.
2849
2850         let chanmon_cfgs = create_chanmon_cfgs(3);
2851         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2852         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2853         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2854
2855         // Create some initial channels
2856         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2857         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2858
2859         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2860         // Get the will-be-revoked local txn from nodes[2]
2861         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2862         // Revoke the old state
2863         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2864
2865         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2866
2867         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2868         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2869         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2870         check_added_monitors!(nodes[1], 1);
2871         check_closed_broadcast!(nodes[1], true);
2872
2873         expect_pending_htlcs_forwardable!(nodes[1]);
2874         check_added_monitors!(nodes[1], 1);
2875         let events = nodes[1].node.get_and_clear_pending_msg_events();
2876         assert_eq!(events.len(), 1);
2877         match events[0] {
2878                 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, .. } } => {
2879                         assert!(update_add_htlcs.is_empty());
2880                         assert_eq!(update_fail_htlcs.len(), 1);
2881                         assert!(update_fulfill_htlcs.is_empty());
2882                         assert!(update_fail_malformed_htlcs.is_empty());
2883                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2884
2885                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2886                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2887                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
2888                 },
2889                 _ => panic!("Unexpected event"),
2890         }
2891 }
2892
2893 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2894         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2895         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2896         // commitment transaction anymore.
2897         // To do this, we have the peer which will broadcast a revoked commitment transaction send
2898         // a number of update_fail/commitment_signed updates without ever sending the RAA in
2899         // response to our commitment_signed. This is somewhat misbehavior-y, though not
2900         // technically disallowed and we should probably handle it reasonably.
2901         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2902         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2903         // transactions:
2904         // * Once we move it out of our holding cell/add it, we will immediately include it in a
2905         //   commitment_signed (implying it will be in the latest remote commitment transaction).
2906         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2907         //   and once they revoke the previous commitment transaction (allowing us to send a new
2908         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2909         let chanmon_cfgs = create_chanmon_cfgs(3);
2910         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2911         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2912         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2913
2914         // Create some initial channels
2915         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2916         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2917
2918         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 });
2919         // Get the will-be-revoked local txn from nodes[2]
2920         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2921         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2922         // Revoke the old state
2923         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2924
2925         let value = if use_dust {
2926                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2927                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2928                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
2929         } else { 3000000 };
2930
2931         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2932         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2933         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2934
2935         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2936         expect_pending_htlcs_forwardable!(nodes[2]);
2937         check_added_monitors!(nodes[2], 1);
2938         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2939         assert!(updates.update_add_htlcs.is_empty());
2940         assert!(updates.update_fulfill_htlcs.is_empty());
2941         assert!(updates.update_fail_malformed_htlcs.is_empty());
2942         assert_eq!(updates.update_fail_htlcs.len(), 1);
2943         assert!(updates.update_fee.is_none());
2944         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2945         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2946         // Drop the last RAA from 3 -> 2
2947
2948         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2949         expect_pending_htlcs_forwardable!(nodes[2]);
2950         check_added_monitors!(nodes[2], 1);
2951         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2952         assert!(updates.update_add_htlcs.is_empty());
2953         assert!(updates.update_fulfill_htlcs.is_empty());
2954         assert!(updates.update_fail_malformed_htlcs.is_empty());
2955         assert_eq!(updates.update_fail_htlcs.len(), 1);
2956         assert!(updates.update_fee.is_none());
2957         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2958         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2959         check_added_monitors!(nodes[1], 1);
2960         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2961         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2962         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2963         check_added_monitors!(nodes[2], 1);
2964
2965         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2966         expect_pending_htlcs_forwardable!(nodes[2]);
2967         check_added_monitors!(nodes[2], 1);
2968         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2969         assert!(updates.update_add_htlcs.is_empty());
2970         assert!(updates.update_fulfill_htlcs.is_empty());
2971         assert!(updates.update_fail_malformed_htlcs.is_empty());
2972         assert_eq!(updates.update_fail_htlcs.len(), 1);
2973         assert!(updates.update_fee.is_none());
2974         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2975         // At this point first_payment_hash has dropped out of the latest two commitment
2976         // transactions that nodes[1] is tracking...
2977         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2978         check_added_monitors!(nodes[1], 1);
2979         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2980         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2981         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2982         check_added_monitors!(nodes[2], 1);
2983
2984         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2985         // on nodes[2]'s RAA.
2986         let (_, fourth_payment_hash, fourth_payment_secret) = get_payment_preimage_hash!(nodes[2]);
2987         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2988         let logger = test_utils::TestLogger::new();
2989         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
2990         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
2991         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2992         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2993         check_added_monitors!(nodes[1], 0);
2994
2995         if deliver_bs_raa {
2996                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2997                 // One monitor for the new revocation preimage, no second on as we won't generate a new
2998                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2999                 check_added_monitors!(nodes[1], 1);
3000                 let events = nodes[1].node.get_and_clear_pending_events();
3001                 assert_eq!(events.len(), 1);
3002                 match events[0] {
3003                         Event::PendingHTLCsForwardable { .. } => { },
3004                         _ => panic!("Unexpected event"),
3005                 };
3006                 // Deliberately don't process the pending fail-back so they all fail back at once after
3007                 // block connection just like the !deliver_bs_raa case
3008         }
3009
3010         let mut failed_htlcs = HashSet::new();
3011         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3012
3013         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3014         check_added_monitors!(nodes[1], 1);
3015         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3016
3017         let events = nodes[1].node.get_and_clear_pending_events();
3018         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3019         match events[0] {
3020                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3021                 _ => panic!("Unexepected event"),
3022         }
3023         match events[1] {
3024                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3025                         assert_eq!(*payment_hash, fourth_payment_hash);
3026                 },
3027                 _ => panic!("Unexpected event"),
3028         }
3029         if !deliver_bs_raa {
3030                 match events[2] {
3031                         Event::PendingHTLCsForwardable { .. } => { },
3032                         _ => panic!("Unexpected event"),
3033                 };
3034         }
3035         nodes[1].node.process_pending_htlc_forwards();
3036         check_added_monitors!(nodes[1], 1);
3037
3038         let events = nodes[1].node.get_and_clear_pending_msg_events();
3039         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3040         match events[if deliver_bs_raa { 1 } else { 0 }] {
3041                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3042                 _ => panic!("Unexpected event"),
3043         }
3044         match events[if deliver_bs_raa { 2 } else { 1 }] {
3045                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3046                         assert_eq!(channel_id, chan_2.2);
3047                         assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3048                 },
3049                 _ => panic!("Unexpected event"),
3050         }
3051         if deliver_bs_raa {
3052                 match events[0] {
3053                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3054                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3055                                 assert_eq!(update_add_htlcs.len(), 1);
3056                                 assert!(update_fulfill_htlcs.is_empty());
3057                                 assert!(update_fail_htlcs.is_empty());
3058                                 assert!(update_fail_malformed_htlcs.is_empty());
3059                         },
3060                         _ => panic!("Unexpected event"),
3061                 }
3062         }
3063         match events[if deliver_bs_raa { 3 } else { 2 }] {
3064                 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, .. } } => {
3065                         assert!(update_add_htlcs.is_empty());
3066                         assert_eq!(update_fail_htlcs.len(), 3);
3067                         assert!(update_fulfill_htlcs.is_empty());
3068                         assert!(update_fail_malformed_htlcs.is_empty());
3069                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3070
3071                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3072                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3073                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3074
3075                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3076
3077                         let events = nodes[0].node.get_and_clear_pending_events();
3078                         assert_eq!(events.len(), 3);
3079                         match events[0] {
3080                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3081                                         assert!(failed_htlcs.insert(payment_hash.0));
3082                                         // If we delivered B's RAA we got an unknown preimage error, not something
3083                                         // that we should update our routing table for.
3084                                         if !deliver_bs_raa {
3085                                                 assert!(network_update.is_some());
3086                                         }
3087                                 },
3088                                 _ => panic!("Unexpected event"),
3089                         }
3090                         match events[1] {
3091                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3092                                         assert!(failed_htlcs.insert(payment_hash.0));
3093                                         assert!(network_update.is_some());
3094                                 },
3095                                 _ => panic!("Unexpected event"),
3096                         }
3097                         match events[2] {
3098                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3099                                         assert!(failed_htlcs.insert(payment_hash.0));
3100                                         assert!(network_update.is_some());
3101                                 },
3102                                 _ => panic!("Unexpected event"),
3103                         }
3104                 },
3105                 _ => panic!("Unexpected event"),
3106         }
3107
3108         assert!(failed_htlcs.contains(&first_payment_hash.0));
3109         assert!(failed_htlcs.contains(&second_payment_hash.0));
3110         assert!(failed_htlcs.contains(&third_payment_hash.0));
3111 }
3112
3113 #[test]
3114 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3115         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3116         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3117         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3118         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3119 }
3120
3121 #[test]
3122 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3123         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3124         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3125         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3126         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3127 }
3128
3129 #[test]
3130 fn fail_backward_pending_htlc_upon_channel_failure() {
3131         let chanmon_cfgs = create_chanmon_cfgs(2);
3132         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3133         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3134         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3135         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3136         let logger = test_utils::TestLogger::new();
3137
3138         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3139         {
3140                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1]);
3141                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3142                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3143                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3144                 check_added_monitors!(nodes[0], 1);
3145
3146                 let payment_event = {
3147                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3148                         assert_eq!(events.len(), 1);
3149                         SendEvent::from_event(events.remove(0))
3150                 };
3151                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3152                 assert_eq!(payment_event.msgs.len(), 1);
3153         }
3154
3155         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3156         let (_, failed_payment_hash, failed_payment_secret) = get_payment_preimage_hash!(nodes[1]);
3157         {
3158                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3159                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3160                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3161                 check_added_monitors!(nodes[0], 0);
3162
3163                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3164         }
3165
3166         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3167         {
3168                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
3169
3170                 let secp_ctx = Secp256k1::new();
3171                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3172                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3173                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3174                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3175                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3176                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3177                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3178
3179                 // Send a 0-msat update_add_htlc to fail the channel.
3180                 let update_add_htlc = msgs::UpdateAddHTLC {
3181                         channel_id: chan.2,
3182                         htlc_id: 0,
3183                         amount_msat: 0,
3184                         payment_hash,
3185                         cltv_expiry,
3186                         onion_routing_packet,
3187                 };
3188                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3189         }
3190         let events = nodes[0].node.get_and_clear_pending_events();
3191         assert_eq!(events.len(), 2);
3192         // Check that Alice fails backward the pending HTLC from the second payment.
3193         match events[0] {
3194                 Event::PaymentPathFailed { payment_hash, .. } => {
3195                         assert_eq!(payment_hash, failed_payment_hash);
3196                 },
3197                 _ => panic!("Unexpected event"),
3198         }
3199         match events[1] {
3200                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3201                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3202                 },
3203                 _ => panic!("Unexpected event {:?}", events[1]),
3204         }
3205         check_closed_broadcast!(nodes[0], true);
3206         check_added_monitors!(nodes[0], 1);
3207 }
3208
3209 #[test]
3210 fn test_htlc_ignore_latest_remote_commitment() {
3211         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3212         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3213         let chanmon_cfgs = create_chanmon_cfgs(2);
3214         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3215         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3216         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3217         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3218
3219         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3220         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3221         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3222         check_closed_broadcast!(nodes[0], true);
3223         check_added_monitors!(nodes[0], 1);
3224         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3225
3226         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3227         assert_eq!(node_txn.len(), 3);
3228         assert_eq!(node_txn[0], node_txn[1]);
3229
3230         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3231         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3232         check_closed_broadcast!(nodes[1], true);
3233         check_added_monitors!(nodes[1], 1);
3234         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3235
3236         // Duplicate the connect_block call since this may happen due to other listeners
3237         // registering new transactions
3238         header.prev_blockhash = header.block_hash();
3239         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3240 }
3241
3242 #[test]
3243 fn test_force_close_fail_back() {
3244         // Check which HTLCs are failed-backwards on channel force-closure
3245         let chanmon_cfgs = create_chanmon_cfgs(3);
3246         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3247         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3248         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3249         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3250         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3251         let logger = test_utils::TestLogger::new();
3252
3253         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
3254
3255         let mut payment_event = {
3256                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3257                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, 42, &logger).unwrap();
3258                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3259                 check_added_monitors!(nodes[0], 1);
3260
3261                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3262                 assert_eq!(events.len(), 1);
3263                 SendEvent::from_event(events.remove(0))
3264         };
3265
3266         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3267         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3268
3269         expect_pending_htlcs_forwardable!(nodes[1]);
3270
3271         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3272         assert_eq!(events_2.len(), 1);
3273         payment_event = SendEvent::from_event(events_2.remove(0));
3274         assert_eq!(payment_event.msgs.len(), 1);
3275
3276         check_added_monitors!(nodes[1], 1);
3277         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3278         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3279         check_added_monitors!(nodes[2], 1);
3280         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3281
3282         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3283         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3284         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3285
3286         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3287         check_closed_broadcast!(nodes[2], true);
3288         check_added_monitors!(nodes[2], 1);
3289         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3290         let tx = {
3291                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3292                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3293                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3294                 // back to nodes[1] upon timeout otherwise.
3295                 assert_eq!(node_txn.len(), 1);
3296                 node_txn.remove(0)
3297         };
3298
3299         mine_transaction(&nodes[1], &tx);
3300
3301         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3302         check_closed_broadcast!(nodes[1], true);
3303         check_added_monitors!(nodes[1], 1);
3304         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3305
3306         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3307         {
3308                 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3309                 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3310                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3311         }
3312         mine_transaction(&nodes[2], &tx);
3313         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3314         assert_eq!(node_txn.len(), 1);
3315         assert_eq!(node_txn[0].input.len(), 1);
3316         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3317         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3318         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3319
3320         check_spends!(node_txn[0], tx);
3321 }
3322
3323 #[test]
3324 fn test_dup_events_on_peer_disconnect() {
3325         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3326         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3327         // as we used to generate the event immediately upon receipt of the payment preimage in the
3328         // update_fulfill_htlc message.
3329
3330         let chanmon_cfgs = create_chanmon_cfgs(2);
3331         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3332         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3333         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3334         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3335
3336         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3337
3338         assert!(nodes[1].node.claim_funds(payment_preimage));
3339         check_added_monitors!(nodes[1], 1);
3340         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3341         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3342         expect_payment_sent!(nodes[0], payment_preimage);
3343
3344         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3345         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3346
3347         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3348         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3349 }
3350
3351 #[test]
3352 fn test_simple_peer_disconnect() {
3353         // Test that we can reconnect when there are no lost messages
3354         let chanmon_cfgs = create_chanmon_cfgs(3);
3355         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3356         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3357         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3358         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3359         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3360
3361         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3362         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3363         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3364
3365         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3366         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3367         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3368         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3369
3370         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3371         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3372         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3373
3374         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3375         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3376         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3377         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3378
3379         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3380         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3381
3382         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3383         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3384
3385         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3386         {
3387                 let events = nodes[0].node.get_and_clear_pending_events();
3388                 assert_eq!(events.len(), 2);
3389                 match events[0] {
3390                         Event::PaymentSent { payment_preimage, payment_hash } => {
3391                                 assert_eq!(payment_preimage, payment_preimage_3);
3392                                 assert_eq!(payment_hash, payment_hash_3);
3393                         },
3394                         _ => panic!("Unexpected event"),
3395                 }
3396                 match events[1] {
3397                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3398                                 assert_eq!(payment_hash, payment_hash_5);
3399                                 assert!(rejected_by_dest);
3400                         },
3401                         _ => panic!("Unexpected event"),
3402                 }
3403         }
3404
3405         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3406         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3407 }
3408
3409 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3410         // Test that we can reconnect when in-flight HTLC updates get dropped
3411         let chanmon_cfgs = create_chanmon_cfgs(2);
3412         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3413         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3414         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3415
3416         let mut as_funding_locked = None;
3417         if messages_delivered == 0 {
3418                 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3419                 as_funding_locked = Some(funding_locked);
3420                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3421                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3422                 // it before the channel_reestablish message.
3423         } else {
3424                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3425         }
3426
3427         let (payment_preimage_1, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[1]);
3428
3429         let logger = test_utils::TestLogger::new();
3430         let payment_event = {
3431                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3432                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph,
3433                         &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3434                         &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3435                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3436                 check_added_monitors!(nodes[0], 1);
3437
3438                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3439                 assert_eq!(events.len(), 1);
3440                 SendEvent::from_event(events.remove(0))
3441         };
3442         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3443
3444         if messages_delivered < 2 {
3445                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3446         } else {
3447                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3448                 if messages_delivered >= 3 {
3449                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3450                         check_added_monitors!(nodes[1], 1);
3451                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3452
3453                         if messages_delivered >= 4 {
3454                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3455                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3456                                 check_added_monitors!(nodes[0], 1);
3457
3458                                 if messages_delivered >= 5 {
3459                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3460                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3461                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3462                                         check_added_monitors!(nodes[0], 1);
3463
3464                                         if messages_delivered >= 6 {
3465                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3466                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3467                                                 check_added_monitors!(nodes[1], 1);
3468                                         }
3469                                 }
3470                         }
3471                 }
3472         }
3473
3474         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3475         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3476         if messages_delivered < 3 {
3477                 if simulate_broken_lnd {
3478                         // lnd has a long-standing bug where they send a funding_locked prior to a
3479                         // channel_reestablish if you reconnect prior to funding_locked time.
3480                         //
3481                         // Here we simulate that behavior, delivering a funding_locked immediately on
3482                         // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3483                         // in `reconnect_nodes` but we currently don't fail based on that.
3484                         //
3485                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3486                         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3487                 }
3488                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3489                 // received on either side, both sides will need to resend them.
3490                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3491         } else if messages_delivered == 3 {
3492                 // nodes[0] still wants its RAA + commitment_signed
3493                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3494         } else if messages_delivered == 4 {
3495                 // nodes[0] still wants its commitment_signed
3496                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3497         } else if messages_delivered == 5 {
3498                 // nodes[1] still wants its final RAA
3499                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3500         } else if messages_delivered == 6 {
3501                 // Everything was delivered...
3502                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3503         }
3504
3505         let events_1 = nodes[1].node.get_and_clear_pending_events();
3506         assert_eq!(events_1.len(), 1);
3507         match events_1[0] {
3508                 Event::PendingHTLCsForwardable { .. } => { },
3509                 _ => panic!("Unexpected event"),
3510         };
3511
3512         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3513         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3514         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3515
3516         nodes[1].node.process_pending_htlc_forwards();
3517
3518         let events_2 = nodes[1].node.get_and_clear_pending_events();
3519         assert_eq!(events_2.len(), 1);
3520         match events_2[0] {
3521                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3522                         assert_eq!(payment_hash_1, *payment_hash);
3523                         assert_eq!(amt, 1000000);
3524                         match &purpose {
3525                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3526                                         assert!(payment_preimage.is_none());
3527                                         assert_eq!(payment_secret_1, *payment_secret);
3528                                 },
3529                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3530                         }
3531                 },
3532                 _ => panic!("Unexpected event"),
3533         }
3534
3535         nodes[1].node.claim_funds(payment_preimage_1);
3536         check_added_monitors!(nodes[1], 1);
3537
3538         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3539         assert_eq!(events_3.len(), 1);
3540         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3541                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3542                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3543                         assert!(updates.update_add_htlcs.is_empty());
3544                         assert!(updates.update_fail_htlcs.is_empty());
3545                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3546                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3547                         assert!(updates.update_fee.is_none());
3548                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3549                 },
3550                 _ => panic!("Unexpected event"),
3551         };
3552
3553         if messages_delivered >= 1 {
3554                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3555
3556                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3557                 assert_eq!(events_4.len(), 1);
3558                 match events_4[0] {
3559                         Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3560                                 assert_eq!(payment_preimage_1, *payment_preimage);
3561                                 assert_eq!(payment_hash_1, *payment_hash);
3562                         },
3563                         _ => panic!("Unexpected event"),
3564                 }
3565
3566                 if messages_delivered >= 2 {
3567                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3568                         check_added_monitors!(nodes[0], 1);
3569                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3570
3571                         if messages_delivered >= 3 {
3572                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3573                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3574                                 check_added_monitors!(nodes[1], 1);
3575
3576                                 if messages_delivered >= 4 {
3577                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3578                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3579                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3580                                         check_added_monitors!(nodes[1], 1);
3581
3582                                         if messages_delivered >= 5 {
3583                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3584                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3585                                                 check_added_monitors!(nodes[0], 1);
3586                                         }
3587                                 }
3588                         }
3589                 }
3590         }
3591
3592         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3593         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3594         if messages_delivered < 2 {
3595                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3596                 if messages_delivered < 1 {
3597                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3598                         assert_eq!(events_4.len(), 1);
3599                         match events_4[0] {
3600                                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3601                                         assert_eq!(payment_preimage_1, *payment_preimage);
3602                                         assert_eq!(payment_hash_1, *payment_hash);
3603                                 },
3604                                 _ => panic!("Unexpected event"),
3605                         }
3606                 } else {
3607                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3608                 }
3609         } else if messages_delivered == 2 {
3610                 // nodes[0] still wants its RAA + commitment_signed
3611                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3612         } else if messages_delivered == 3 {
3613                 // nodes[0] still wants its commitment_signed
3614                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3615         } else if messages_delivered == 4 {
3616                 // nodes[1] still wants its final RAA
3617                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3618         } else if messages_delivered == 5 {
3619                 // Everything was delivered...
3620                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3621         }
3622
3623         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3624         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3625         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3626
3627         // Channel should still work fine...
3628         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3629         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph,
3630                 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3631                 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3632         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3633         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3634 }
3635
3636 #[test]
3637 fn test_drop_messages_peer_disconnect_a() {
3638         do_test_drop_messages_peer_disconnect(0, true);
3639         do_test_drop_messages_peer_disconnect(0, false);
3640         do_test_drop_messages_peer_disconnect(1, false);
3641         do_test_drop_messages_peer_disconnect(2, false);
3642 }
3643
3644 #[test]
3645 fn test_drop_messages_peer_disconnect_b() {
3646         do_test_drop_messages_peer_disconnect(3, false);
3647         do_test_drop_messages_peer_disconnect(4, false);
3648         do_test_drop_messages_peer_disconnect(5, false);
3649         do_test_drop_messages_peer_disconnect(6, false);
3650 }
3651
3652 #[test]
3653 fn test_funding_peer_disconnect() {
3654         // Test that we can lock in our funding tx while disconnected
3655         let chanmon_cfgs = create_chanmon_cfgs(2);
3656         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3657         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3658         let persister: test_utils::TestPersister;
3659         let new_chain_monitor: test_utils::TestChainMonitor;
3660         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3661         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3662         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3663
3664         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3665         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3666
3667         confirm_transaction(&nodes[0], &tx);
3668         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3669         assert_eq!(events_1.len(), 1);
3670         match events_1[0] {
3671                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3672                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3673                 },
3674                 _ => panic!("Unexpected event"),
3675         }
3676
3677         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3678
3679         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3680         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3681
3682         confirm_transaction(&nodes[1], &tx);
3683         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3684         assert_eq!(events_2.len(), 2);
3685         let funding_locked = match events_2[0] {
3686                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3687                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3688                         msg.clone()
3689                 },
3690                 _ => panic!("Unexpected event"),
3691         };
3692         let bs_announcement_sigs = match events_2[1] {
3693                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3694                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3695                         msg.clone()
3696                 },
3697                 _ => panic!("Unexpected event"),
3698         };
3699
3700         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3701
3702         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3703         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3704         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3705         assert_eq!(events_3.len(), 2);
3706         let as_announcement_sigs = match events_3[0] {
3707                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3708                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3709                         msg.clone()
3710                 },
3711                 _ => panic!("Unexpected event"),
3712         };
3713         let (as_announcement, as_update) = match events_3[1] {
3714                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3715                         (msg.clone(), update_msg.clone())
3716                 },
3717                 _ => panic!("Unexpected event"),
3718         };
3719
3720         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3721         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3722         assert_eq!(events_4.len(), 1);
3723         let (_, bs_update) = match events_4[0] {
3724                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3725                         (msg.clone(), update_msg.clone())
3726                 },
3727                 _ => panic!("Unexpected event"),
3728         };
3729
3730         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3731         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3732         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3733
3734         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3735         let logger = test_utils::TestLogger::new();
3736         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3737         let (payment_preimage, _, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3738         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3739
3740         // Check that after deserialization and reconnection we can still generate an identical
3741         // channel_announcement from the cached signatures.
3742         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3743
3744         let nodes_0_serialized = nodes[0].node.encode();
3745         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3746         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
3747
3748         persister = test_utils::TestPersister::new();
3749         let keys_manager = &chanmon_cfgs[0].keys_manager;
3750         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);
3751         nodes[0].chain_monitor = &new_chain_monitor;
3752         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3753         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3754                 &mut chan_0_monitor_read, keys_manager).unwrap();
3755         assert!(chan_0_monitor_read.is_empty());
3756
3757         let mut nodes_0_read = &nodes_0_serialized[..];
3758         let (_, nodes_0_deserialized_tmp) = {
3759                 let mut channel_monitors = HashMap::new();
3760                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3761                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3762                         default_config: UserConfig::default(),
3763                         keys_manager,
3764                         fee_estimator: node_cfgs[0].fee_estimator,
3765                         chain_monitor: nodes[0].chain_monitor,
3766                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3767                         logger: nodes[0].logger,
3768                         channel_monitors,
3769                 }).unwrap()
3770         };
3771         nodes_0_deserialized = nodes_0_deserialized_tmp;
3772         assert!(nodes_0_read.is_empty());
3773
3774         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3775         nodes[0].node = &nodes_0_deserialized;
3776         check_added_monitors!(nodes[0], 1);
3777
3778         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3779
3780         // as_announcement should be re-generated exactly by broadcast_node_announcement.
3781         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3782         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3783         let mut found_announcement = false;
3784         for event in msgs.iter() {
3785                 match event {
3786                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3787                                 if *msg == as_announcement { found_announcement = true; }
3788                         },
3789                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3790                         _ => panic!("Unexpected event"),
3791                 }
3792         }
3793         assert!(found_announcement);
3794 }
3795
3796 #[test]
3797 fn test_drop_messages_peer_disconnect_dual_htlc() {
3798         // Test that we can handle reconnecting when both sides of a channel have pending
3799         // commitment_updates when we disconnect.
3800         let chanmon_cfgs = create_chanmon_cfgs(2);
3801         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3802         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3803         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3804         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3805         let logger = test_utils::TestLogger::new();
3806
3807         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3808
3809         // Now try to send a second payment which will fail to send
3810         let (payment_preimage_2, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
3811         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3812         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3813         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3814         check_added_monitors!(nodes[0], 1);
3815
3816         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3817         assert_eq!(events_1.len(), 1);
3818         match events_1[0] {
3819                 MessageSendEvent::UpdateHTLCs { .. } => {},
3820                 _ => panic!("Unexpected event"),
3821         }
3822
3823         assert!(nodes[1].node.claim_funds(payment_preimage_1));
3824         check_added_monitors!(nodes[1], 1);
3825
3826         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3827         assert_eq!(events_2.len(), 1);
3828         match events_2[0] {
3829                 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 } } => {
3830                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3831                         assert!(update_add_htlcs.is_empty());
3832                         assert_eq!(update_fulfill_htlcs.len(), 1);
3833                         assert!(update_fail_htlcs.is_empty());
3834                         assert!(update_fail_malformed_htlcs.is_empty());
3835                         assert!(update_fee.is_none());
3836
3837                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3838                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3839                         assert_eq!(events_3.len(), 1);
3840                         match events_3[0] {
3841                                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3842                                         assert_eq!(*payment_preimage, payment_preimage_1);
3843                                         assert_eq!(*payment_hash, payment_hash_1);
3844                                 },
3845                                 _ => panic!("Unexpected event"),
3846                         }
3847
3848                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3849                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3850                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3851                         check_added_monitors!(nodes[0], 1);
3852                 },
3853                 _ => panic!("Unexpected event"),
3854         }
3855
3856         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3857         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3858
3859         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3860         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3861         assert_eq!(reestablish_1.len(), 1);
3862         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3863         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3864         assert_eq!(reestablish_2.len(), 1);
3865
3866         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3867         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3868         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3869         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3870
3871         assert!(as_resp.0.is_none());
3872         assert!(bs_resp.0.is_none());
3873
3874         assert!(bs_resp.1.is_none());
3875         assert!(bs_resp.2.is_none());
3876
3877         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3878
3879         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3880         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3881         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3882         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3883         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3884         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3885         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3886         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3887         // No commitment_signed so get_event_msg's assert(len == 1) passes
3888         check_added_monitors!(nodes[1], 1);
3889
3890         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3891         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3892         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3893         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3894         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3895         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3896         assert!(bs_second_commitment_signed.update_fee.is_none());
3897         check_added_monitors!(nodes[1], 1);
3898
3899         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3900         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3901         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3902         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3903         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3904         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3905         assert!(as_commitment_signed.update_fee.is_none());
3906         check_added_monitors!(nodes[0], 1);
3907
3908         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3909         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3910         // No commitment_signed so get_event_msg's assert(len == 1) passes
3911         check_added_monitors!(nodes[0], 1);
3912
3913         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3914         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3915         // No commitment_signed so get_event_msg's assert(len == 1) passes
3916         check_added_monitors!(nodes[1], 1);
3917
3918         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3919         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3920         check_added_monitors!(nodes[1], 1);
3921
3922         expect_pending_htlcs_forwardable!(nodes[1]);
3923
3924         let events_5 = nodes[1].node.get_and_clear_pending_events();
3925         assert_eq!(events_5.len(), 1);
3926         match events_5[0] {
3927                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
3928                         assert_eq!(payment_hash_2, *payment_hash);
3929                         match &purpose {
3930                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3931                                         assert!(payment_preimage.is_none());
3932                                         assert_eq!(payment_secret_2, *payment_secret);
3933                                 },
3934                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3935                         }
3936                 },
3937                 _ => panic!("Unexpected event"),
3938         }
3939
3940         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3941         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3942         check_added_monitors!(nodes[0], 1);
3943
3944         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3945 }
3946
3947 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3948         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3949         // to avoid our counterparty failing the channel.
3950         let chanmon_cfgs = create_chanmon_cfgs(2);
3951         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3952         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3953         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3954
3955         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3956         let logger = test_utils::TestLogger::new();
3957
3958         let our_payment_hash = if send_partial_mpp {
3959                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3960                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
3961                 let (_, our_payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[1]);
3962                 // Use the utility function send_payment_along_path to send the payment with MPP data which
3963                 // indicates there are more HTLCs coming.
3964                 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.
3965                 let payment_id = PaymentId([42; 32]);
3966                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
3967                 check_added_monitors!(nodes[0], 1);
3968                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3969                 assert_eq!(events.len(), 1);
3970                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3971                 // hop should *not* yet generate any PaymentReceived event(s).
3972                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
3973                 our_payment_hash
3974         } else {
3975                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3976         };
3977
3978         let mut block = Block {
3979                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3980                 txdata: vec![],
3981         };
3982         connect_block(&nodes[0], &block);
3983         connect_block(&nodes[1], &block);
3984         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
3985         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
3986                 block.header.prev_blockhash = block.block_hash();
3987                 connect_block(&nodes[0], &block);
3988                 connect_block(&nodes[1], &block);
3989         }
3990
3991         expect_pending_htlcs_forwardable!(nodes[1]);
3992
3993         check_added_monitors!(nodes[1], 1);
3994         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3995         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3996         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3997         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3998         assert!(htlc_timeout_updates.update_fee.is_none());
3999
4000         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4001         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4002         // 100_000 msat as u64, followed by the height at which we failed back above
4003         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4004         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4005         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4006 }
4007
4008 #[test]
4009 fn test_htlc_timeout() {
4010         do_test_htlc_timeout(true);
4011         do_test_htlc_timeout(false);
4012 }
4013
4014 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4015         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4016         let chanmon_cfgs = create_chanmon_cfgs(3);
4017         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4018         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4019         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4020         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4021         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4022
4023         // Make sure all nodes are at the same starting height
4024         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4025         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4026         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4027
4028         let logger = test_utils::TestLogger::new();
4029
4030         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4031         let (_, first_payment_hash, first_payment_secret) = get_payment_preimage_hash!(nodes[2]);
4032         {
4033                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4034                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4035                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4036         }
4037         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4038         check_added_monitors!(nodes[1], 1);
4039
4040         // Now attempt to route a second payment, which should be placed in the holding cell
4041         let (_, second_payment_hash, second_payment_secret) = get_payment_preimage_hash!(nodes[2]);
4042         if forwarded_htlc {
4043                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4044                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4045                 nodes[0].node.send_payment(&route, second_payment_hash, &Some(first_payment_secret)).unwrap();
4046                 check_added_monitors!(nodes[0], 1);
4047                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4048                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4049                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4050                 expect_pending_htlcs_forwardable!(nodes[1]);
4051                 check_added_monitors!(nodes[1], 0);
4052         } else {
4053                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4054                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4055                 nodes[1].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4056                 check_added_monitors!(nodes[1], 0);
4057         }
4058
4059         connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4060         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4061         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4062         connect_blocks(&nodes[1], 1);
4063
4064         if forwarded_htlc {
4065                 expect_pending_htlcs_forwardable!(nodes[1]);
4066                 check_added_monitors!(nodes[1], 1);
4067                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4068                 assert_eq!(fail_commit.len(), 1);
4069                 match fail_commit[0] {
4070                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4071                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4072                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4073                         },
4074                         _ => unreachable!(),
4075                 }
4076                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4077         } else {
4078                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4079         }
4080 }
4081
4082 #[test]
4083 fn test_holding_cell_htlc_add_timeouts() {
4084         do_test_holding_cell_htlc_add_timeouts(false);
4085         do_test_holding_cell_htlc_add_timeouts(true);
4086 }
4087
4088 #[test]
4089 fn test_no_txn_manager_serialize_deserialize() {
4090         let chanmon_cfgs = create_chanmon_cfgs(2);
4091         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4092         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4093         let logger: test_utils::TestLogger;
4094         let fee_estimator: test_utils::TestFeeEstimator;
4095         let persister: test_utils::TestPersister;
4096         let new_chain_monitor: test_utils::TestChainMonitor;
4097         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4098         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4099
4100         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4101
4102         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4103
4104         let nodes_0_serialized = nodes[0].node.encode();
4105         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4106         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4107
4108         logger = test_utils::TestLogger::new();
4109         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4110         persister = test_utils::TestPersister::new();
4111         let keys_manager = &chanmon_cfgs[0].keys_manager;
4112         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4113         nodes[0].chain_monitor = &new_chain_monitor;
4114         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4115         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4116                 &mut chan_0_monitor_read, keys_manager).unwrap();
4117         assert!(chan_0_monitor_read.is_empty());
4118
4119         let mut nodes_0_read = &nodes_0_serialized[..];
4120         let config = UserConfig::default();
4121         let (_, nodes_0_deserialized_tmp) = {
4122                 let mut channel_monitors = HashMap::new();
4123                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4124                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4125                         default_config: config,
4126                         keys_manager,
4127                         fee_estimator: &fee_estimator,
4128                         chain_monitor: nodes[0].chain_monitor,
4129                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4130                         logger: &logger,
4131                         channel_monitors,
4132                 }).unwrap()
4133         };
4134         nodes_0_deserialized = nodes_0_deserialized_tmp;
4135         assert!(nodes_0_read.is_empty());
4136
4137         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4138         nodes[0].node = &nodes_0_deserialized;
4139         assert_eq!(nodes[0].node.list_channels().len(), 1);
4140         check_added_monitors!(nodes[0], 1);
4141
4142         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4143         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4144         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4145         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4146
4147         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4148         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4149         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4150         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4151
4152         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4153         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4154         for node in nodes.iter() {
4155                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4156                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4157                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4158         }
4159
4160         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4161 }
4162
4163 #[test]
4164 fn mpp_failure() {
4165         let chanmon_cfgs = create_chanmon_cfgs(4);
4166         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4167         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4168         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4169
4170         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4171         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4172         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4173         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4174         let logger = test_utils::TestLogger::new();
4175
4176         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[3]);
4177         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4178         let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[3].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
4179         let path = route.paths[0].clone();
4180         route.paths.push(path);
4181         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
4182         route.paths[0][0].short_channel_id = chan_1_id;
4183         route.paths[0][1].short_channel_id = chan_3_id;
4184         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
4185         route.paths[1][0].short_channel_id = chan_2_id;
4186         route.paths[1][1].short_channel_id = chan_4_id;
4187         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
4188         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
4189 }
4190
4191 #[test]
4192 fn test_dup_htlc_onchain_fails_on_reload() {
4193         // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
4194         // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
4195         // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
4196         // the ChannelMonitor tells it to.
4197         //
4198         // If, due to an on-chain event, an HTLC is failed/claimed, and then we serialize the
4199         // ChannelManager, we generally expect there not to be a duplicate HTLC fail/claim (eg via a
4200         // PaymentPathFailed event appearing). However, because we may not serialize the relevant
4201         // ChannelMonitor at the same time, this isn't strictly guaranteed. In order to provide this
4202         // consistency, the ChannelManager explicitly tracks pending-onchain-resolution outbound HTLCs
4203         // and de-duplicates ChannelMonitor events.
4204         //
4205         // This tests that explicit tracking behavior.
4206         let chanmon_cfgs = create_chanmon_cfgs(2);
4207         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4208         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4209         let persister: test_utils::TestPersister;
4210         let new_chain_monitor: test_utils::TestChainMonitor;
4211         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4212         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4213
4214         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4215
4216         // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
4217         // nodes[0].
4218         let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 10000000);
4219         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
4220         check_closed_broadcast!(nodes[0], true);
4221         check_added_monitors!(nodes[0], 1);
4222         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4223
4224         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4225         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4226
4227         // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
4228         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
4229         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4230         assert_eq!(node_txn.len(), 3);
4231         assert_eq!(node_txn[0], node_txn[1]);
4232
4233         assert!(nodes[1].node.claim_funds(payment_preimage));
4234         check_added_monitors!(nodes[1], 1);
4235
4236         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4237         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4238         check_closed_broadcast!(nodes[1], true);
4239         check_added_monitors!(nodes[1], 1);
4240         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4241         let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4242
4243         header.prev_blockhash = nodes[0].best_block_hash();
4244         connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4245
4246         // Serialize out the ChannelMonitor before connecting the on-chain claim transactions. This is
4247         // fairly normal behavior as ChannelMonitor(s) are often not re-serialized when on-chain events
4248         // happen, unlike ChannelManager which tends to be re-serialized after any relevant event(s).
4249         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4250         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4251
4252         header.prev_blockhash = nodes[0].best_block_hash();
4253         let claim_block = Block { header, txdata: claim_txn};
4254         connect_block(&nodes[0], &claim_block);
4255         expect_payment_sent!(nodes[0], payment_preimage);
4256
4257         // ChannelManagers generally get re-serialized after any relevant event(s). Since we just
4258         // connected a highly-relevant block, it likely gets serialized out now.
4259         let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
4260         nodes[0].node.write(&mut chan_manager_serialized).unwrap();
4261
4262         // Now reload nodes[0]...
4263         persister = test_utils::TestPersister::new();
4264         let keys_manager = &chanmon_cfgs[0].keys_manager;
4265         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);
4266         nodes[0].chain_monitor = &new_chain_monitor;
4267         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4268         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4269                 &mut chan_0_monitor_read, keys_manager).unwrap();
4270         assert!(chan_0_monitor_read.is_empty());
4271
4272         let (_, nodes_0_deserialized_tmp) = {
4273                 let mut channel_monitors = HashMap::new();
4274                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4275                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
4276                         ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
4277                                 default_config: Default::default(),
4278                                 keys_manager,
4279                                 fee_estimator: node_cfgs[0].fee_estimator,
4280                                 chain_monitor: nodes[0].chain_monitor,
4281                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4282                                 logger: nodes[0].logger,
4283                                 channel_monitors,
4284                         }).unwrap()
4285         };
4286         nodes_0_deserialized = nodes_0_deserialized_tmp;
4287
4288         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4289         check_added_monitors!(nodes[0], 1);
4290         nodes[0].node = &nodes_0_deserialized;
4291
4292         // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
4293         // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
4294         // payment events should kick in, leaving us with no pending events here.
4295         let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
4296         nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
4297         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4298 }
4299
4300 #[test]
4301 fn test_manager_serialize_deserialize_events() {
4302         // This test makes sure the events field in ChannelManager survives de/serialization
4303         let chanmon_cfgs = create_chanmon_cfgs(2);
4304         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4305         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4306         let fee_estimator: test_utils::TestFeeEstimator;
4307         let persister: test_utils::TestPersister;
4308         let logger: test_utils::TestLogger;
4309         let new_chain_monitor: test_utils::TestChainMonitor;
4310         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4311         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4312
4313         // Start creating a channel, but stop right before broadcasting the funding transaction
4314         let channel_value = 100000;
4315         let push_msat = 10001;
4316         let a_flags = InitFeatures::known();
4317         let b_flags = InitFeatures::known();
4318         let node_a = nodes.remove(0);
4319         let node_b = nodes.remove(0);
4320         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4321         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()));
4322         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()));
4323
4324         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4325
4326         node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4327         check_added_monitors!(node_a, 0);
4328
4329         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()));
4330         {
4331                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4332                 assert_eq!(added_monitors.len(), 1);
4333                 assert_eq!(added_monitors[0].0, funding_output);
4334                 added_monitors.clear();
4335         }
4336
4337         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()));
4338         {
4339                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4340                 assert_eq!(added_monitors.len(), 1);
4341                 assert_eq!(added_monitors[0].0, funding_output);
4342                 added_monitors.clear();
4343         }
4344         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4345
4346         nodes.push(node_a);
4347         nodes.push(node_b);
4348
4349         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4350         let nodes_0_serialized = nodes[0].node.encode();
4351         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4352         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4353
4354         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4355         logger = test_utils::TestLogger::new();
4356         persister = test_utils::TestPersister::new();
4357         let keys_manager = &chanmon_cfgs[0].keys_manager;
4358         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4359         nodes[0].chain_monitor = &new_chain_monitor;
4360         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4361         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4362                 &mut chan_0_monitor_read, keys_manager).unwrap();
4363         assert!(chan_0_monitor_read.is_empty());
4364
4365         let mut nodes_0_read = &nodes_0_serialized[..];
4366         let config = UserConfig::default();
4367         let (_, nodes_0_deserialized_tmp) = {
4368                 let mut channel_monitors = HashMap::new();
4369                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4370                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4371                         default_config: config,
4372                         keys_manager,
4373                         fee_estimator: &fee_estimator,
4374                         chain_monitor: nodes[0].chain_monitor,
4375                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4376                         logger: &logger,
4377                         channel_monitors,
4378                 }).unwrap()
4379         };
4380         nodes_0_deserialized = nodes_0_deserialized_tmp;
4381         assert!(nodes_0_read.is_empty());
4382
4383         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4384
4385         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4386         nodes[0].node = &nodes_0_deserialized;
4387
4388         // After deserializing, make sure the funding_transaction is still held by the channel manager
4389         let events_4 = nodes[0].node.get_and_clear_pending_events();
4390         assert_eq!(events_4.len(), 0);
4391         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4392         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4393
4394         // Make sure the channel is functioning as though the de/serialization never happened
4395         assert_eq!(nodes[0].node.list_channels().len(), 1);
4396         check_added_monitors!(nodes[0], 1);
4397
4398         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4399         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4400         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4401         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4402
4403         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4404         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4405         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4406         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4407
4408         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4409         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4410         for node in nodes.iter() {
4411                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4412                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4413                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4414         }
4415
4416         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4417 }
4418
4419 #[test]
4420 fn test_simple_manager_serialize_deserialize() {
4421         let chanmon_cfgs = create_chanmon_cfgs(2);
4422         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4423         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4424         let logger: test_utils::TestLogger;
4425         let fee_estimator: test_utils::TestFeeEstimator;
4426         let persister: test_utils::TestPersister;
4427         let new_chain_monitor: test_utils::TestChainMonitor;
4428         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4429         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4430         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4431
4432         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4433         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4434
4435         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4436
4437         let nodes_0_serialized = nodes[0].node.encode();
4438         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4439         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4440
4441         logger = test_utils::TestLogger::new();
4442         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4443         persister = test_utils::TestPersister::new();
4444         let keys_manager = &chanmon_cfgs[0].keys_manager;
4445         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4446         nodes[0].chain_monitor = &new_chain_monitor;
4447         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4448         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4449                 &mut chan_0_monitor_read, keys_manager).unwrap();
4450         assert!(chan_0_monitor_read.is_empty());
4451
4452         let mut nodes_0_read = &nodes_0_serialized[..];
4453         let (_, nodes_0_deserialized_tmp) = {
4454                 let mut channel_monitors = HashMap::new();
4455                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4456                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4457                         default_config: UserConfig::default(),
4458                         keys_manager,
4459                         fee_estimator: &fee_estimator,
4460                         chain_monitor: nodes[0].chain_monitor,
4461                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4462                         logger: &logger,
4463                         channel_monitors,
4464                 }).unwrap()
4465         };
4466         nodes_0_deserialized = nodes_0_deserialized_tmp;
4467         assert!(nodes_0_read.is_empty());
4468
4469         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4470         nodes[0].node = &nodes_0_deserialized;
4471         check_added_monitors!(nodes[0], 1);
4472
4473         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4474
4475         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4476         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4477 }
4478
4479 #[test]
4480 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4481         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4482         let chanmon_cfgs = create_chanmon_cfgs(4);
4483         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4484         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4485         let logger: test_utils::TestLogger;
4486         let fee_estimator: test_utils::TestFeeEstimator;
4487         let persister: test_utils::TestPersister;
4488         let new_chain_monitor: test_utils::TestChainMonitor;
4489         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4490         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4491         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4492         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4493         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4494
4495         let mut node_0_stale_monitors_serialized = Vec::new();
4496         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4497                 let mut writer = test_utils::TestVecWriter(Vec::new());
4498                 monitor.1.write(&mut writer).unwrap();
4499                 node_0_stale_monitors_serialized.push(writer.0);
4500         }
4501
4502         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4503
4504         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4505         let nodes_0_serialized = nodes[0].node.encode();
4506
4507         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4508         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4509         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4510         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4511
4512         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4513         // nodes[3])
4514         let mut node_0_monitors_serialized = Vec::new();
4515         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4516                 let mut writer = test_utils::TestVecWriter(Vec::new());
4517                 monitor.1.write(&mut writer).unwrap();
4518                 node_0_monitors_serialized.push(writer.0);
4519         }
4520
4521         logger = test_utils::TestLogger::new();
4522         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4523         persister = test_utils::TestPersister::new();
4524         let keys_manager = &chanmon_cfgs[0].keys_manager;
4525         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4526         nodes[0].chain_monitor = &new_chain_monitor;
4527
4528
4529         let mut node_0_stale_monitors = Vec::new();
4530         for serialized in node_0_stale_monitors_serialized.iter() {
4531                 let mut read = &serialized[..];
4532                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4533                 assert!(read.is_empty());
4534                 node_0_stale_monitors.push(monitor);
4535         }
4536
4537         let mut node_0_monitors = Vec::new();
4538         for serialized in node_0_monitors_serialized.iter() {
4539                 let mut read = &serialized[..];
4540                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4541                 assert!(read.is_empty());
4542                 node_0_monitors.push(monitor);
4543         }
4544
4545         let mut nodes_0_read = &nodes_0_serialized[..];
4546         if let Err(msgs::DecodeError::InvalidValue) =
4547                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4548                 default_config: UserConfig::default(),
4549                 keys_manager,
4550                 fee_estimator: &fee_estimator,
4551                 chain_monitor: nodes[0].chain_monitor,
4552                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4553                 logger: &logger,
4554                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4555         }) { } else {
4556                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4557         };
4558
4559         let mut nodes_0_read = &nodes_0_serialized[..];
4560         let (_, nodes_0_deserialized_tmp) =
4561                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4562                 default_config: UserConfig::default(),
4563                 keys_manager,
4564                 fee_estimator: &fee_estimator,
4565                 chain_monitor: nodes[0].chain_monitor,
4566                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4567                 logger: &logger,
4568                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4569         }).unwrap();
4570         nodes_0_deserialized = nodes_0_deserialized_tmp;
4571         assert!(nodes_0_read.is_empty());
4572
4573         { // Channel close should result in a commitment tx
4574                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4575                 assert_eq!(txn.len(), 1);
4576                 check_spends!(txn[0], funding_tx);
4577                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4578         }
4579
4580         for monitor in node_0_monitors.drain(..) {
4581                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4582                 check_added_monitors!(nodes[0], 1);
4583         }
4584         nodes[0].node = &nodes_0_deserialized;
4585         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4586
4587         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4588         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4589         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4590         //... and we can even still claim the payment!
4591         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4592
4593         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4594         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4595         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4596         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4597         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4598         assert_eq!(msg_events.len(), 1);
4599         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4600                 match action {
4601                         &ErrorAction::SendErrorMessage { ref msg } => {
4602                                 assert_eq!(msg.channel_id, channel_id);
4603                         },
4604                         _ => panic!("Unexpected event!"),
4605                 }
4606         }
4607 }
4608
4609 macro_rules! check_spendable_outputs {
4610         ($node: expr, $keysinterface: expr) => {
4611                 {
4612                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4613                         let mut txn = Vec::new();
4614                         let mut all_outputs = Vec::new();
4615                         let secp_ctx = Secp256k1::new();
4616                         for event in events.drain(..) {
4617                                 match event {
4618                                         Event::SpendableOutputs { mut outputs } => {
4619                                                 for outp in outputs.drain(..) {
4620                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4621                                                         all_outputs.push(outp);
4622                                                 }
4623                                         },
4624                                         _ => panic!("Unexpected event"),
4625                                 };
4626                         }
4627                         if all_outputs.len() > 1 {
4628                                 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) {
4629                                         txn.push(tx);
4630                                 }
4631                         }
4632                         txn
4633                 }
4634         }
4635 }
4636
4637 #[test]
4638 fn test_claim_sizeable_push_msat() {
4639         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4640         let chanmon_cfgs = create_chanmon_cfgs(2);
4641         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4642         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4643         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4644
4645         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4646         nodes[1].node.force_close_channel(&chan.2).unwrap();
4647         check_closed_broadcast!(nodes[1], true);
4648         check_added_monitors!(nodes[1], 1);
4649         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4650         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4651         assert_eq!(node_txn.len(), 1);
4652         check_spends!(node_txn[0], chan.3);
4653         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
4654
4655         mine_transaction(&nodes[1], &node_txn[0]);
4656         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4657
4658         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4659         assert_eq!(spend_txn.len(), 1);
4660         assert_eq!(spend_txn[0].input.len(), 1);
4661         check_spends!(spend_txn[0], node_txn[0]);
4662         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4663 }
4664
4665 #[test]
4666 fn test_claim_on_remote_sizeable_push_msat() {
4667         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4668         // to_remote output is encumbered by a P2WPKH
4669         let chanmon_cfgs = create_chanmon_cfgs(2);
4670         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4671         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4672         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4673
4674         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4675         nodes[0].node.force_close_channel(&chan.2).unwrap();
4676         check_closed_broadcast!(nodes[0], true);
4677         check_added_monitors!(nodes[0], 1);
4678         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4679
4680         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4681         assert_eq!(node_txn.len(), 1);
4682         check_spends!(node_txn[0], chan.3);
4683         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
4684
4685         mine_transaction(&nodes[1], &node_txn[0]);
4686         check_closed_broadcast!(nodes[1], true);
4687         check_added_monitors!(nodes[1], 1);
4688         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4689         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4690
4691         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4692         assert_eq!(spend_txn.len(), 1);
4693         check_spends!(spend_txn[0], node_txn[0]);
4694 }
4695
4696 #[test]
4697 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4698         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4699         // to_remote output is encumbered by a P2WPKH
4700
4701         let chanmon_cfgs = create_chanmon_cfgs(2);
4702         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4703         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4704         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4705
4706         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4707         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4708         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4709         assert_eq!(revoked_local_txn[0].input.len(), 1);
4710         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4711
4712         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4713         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4714         check_closed_broadcast!(nodes[1], true);
4715         check_added_monitors!(nodes[1], 1);
4716         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4717
4718         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4719         mine_transaction(&nodes[1], &node_txn[0]);
4720         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4721
4722         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4723         assert_eq!(spend_txn.len(), 3);
4724         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4725         check_spends!(spend_txn[1], node_txn[0]);
4726         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4727 }
4728
4729 #[test]
4730 fn test_static_spendable_outputs_preimage_tx() {
4731         let chanmon_cfgs = create_chanmon_cfgs(2);
4732         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4733         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4734         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4735
4736         // Create some initial channels
4737         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4738
4739         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4740
4741         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4742         assert_eq!(commitment_tx[0].input.len(), 1);
4743         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4744
4745         // Settle A's commitment tx on B's chain
4746         assert!(nodes[1].node.claim_funds(payment_preimage));
4747         check_added_monitors!(nodes[1], 1);
4748         mine_transaction(&nodes[1], &commitment_tx[0]);
4749         check_added_monitors!(nodes[1], 1);
4750         let events = nodes[1].node.get_and_clear_pending_msg_events();
4751         match events[0] {
4752                 MessageSendEvent::UpdateHTLCs { .. } => {},
4753                 _ => panic!("Unexpected event"),
4754         }
4755         match events[1] {
4756                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4757                 _ => panic!("Unexepected event"),
4758         }
4759
4760         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4761         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4762         assert_eq!(node_txn.len(), 3);
4763         check_spends!(node_txn[0], commitment_tx[0]);
4764         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4765         check_spends!(node_txn[1], chan_1.3);
4766         check_spends!(node_txn[2], node_txn[1]);
4767
4768         mine_transaction(&nodes[1], &node_txn[0]);
4769         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4770         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4771
4772         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4773         assert_eq!(spend_txn.len(), 1);
4774         check_spends!(spend_txn[0], node_txn[0]);
4775 }
4776
4777 #[test]
4778 fn test_static_spendable_outputs_timeout_tx() {
4779         let chanmon_cfgs = create_chanmon_cfgs(2);
4780         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4781         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4782         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4783
4784         // Create some initial channels
4785         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4786
4787         // Rebalance the network a bit by relaying one payment through all the channels ...
4788         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4789
4790         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4791
4792         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4793         assert_eq!(commitment_tx[0].input.len(), 1);
4794         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4795
4796         // Settle A's commitment tx on B' chain
4797         mine_transaction(&nodes[1], &commitment_tx[0]);
4798         check_added_monitors!(nodes[1], 1);
4799         let events = nodes[1].node.get_and_clear_pending_msg_events();
4800         match events[0] {
4801                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4802                 _ => panic!("Unexpected event"),
4803         }
4804         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4805
4806         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4807         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4808         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4809         check_spends!(node_txn[0], chan_1.3.clone());
4810         check_spends!(node_txn[1],  commitment_tx[0].clone());
4811         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4812
4813         mine_transaction(&nodes[1], &node_txn[1]);
4814         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4815         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4816         expect_payment_failed!(nodes[1], our_payment_hash, true);
4817
4818         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4819         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4820         check_spends!(spend_txn[0], commitment_tx[0]);
4821         check_spends!(spend_txn[1], node_txn[1]);
4822         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4823 }
4824
4825 #[test]
4826 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4827         let chanmon_cfgs = create_chanmon_cfgs(2);
4828         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4829         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4830         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4831
4832         // Create some initial channels
4833         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4834
4835         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4836         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4837         assert_eq!(revoked_local_txn[0].input.len(), 1);
4838         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4839
4840         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4841
4842         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4843         check_closed_broadcast!(nodes[1], true);
4844         check_added_monitors!(nodes[1], 1);
4845         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4846
4847         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4848         assert_eq!(node_txn.len(), 2);
4849         assert_eq!(node_txn[0].input.len(), 2);
4850         check_spends!(node_txn[0], revoked_local_txn[0]);
4851
4852         mine_transaction(&nodes[1], &node_txn[0]);
4853         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4854
4855         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4856         assert_eq!(spend_txn.len(), 1);
4857         check_spends!(spend_txn[0], node_txn[0]);
4858 }
4859
4860 #[test]
4861 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4862         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4863         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4864         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4865         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4866         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4867
4868         // Create some initial channels
4869         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4870
4871         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4872         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4873         assert_eq!(revoked_local_txn[0].input.len(), 1);
4874         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4875
4876         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4877
4878         // A will generate HTLC-Timeout from revoked commitment tx
4879         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4880         check_closed_broadcast!(nodes[0], true);
4881         check_added_monitors!(nodes[0], 1);
4882         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4883         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4884
4885         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4886         assert_eq!(revoked_htlc_txn.len(), 2);
4887         check_spends!(revoked_htlc_txn[0], chan_1.3);
4888         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4889         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4890         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4891         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4892
4893         // B will generate justice tx from A's revoked commitment/HTLC tx
4894         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4895         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4896         check_closed_broadcast!(nodes[1], true);
4897         check_added_monitors!(nodes[1], 1);
4898         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4899
4900         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4901         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4902         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4903         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4904         // transactions next...
4905         assert_eq!(node_txn[0].input.len(), 3);
4906         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4907
4908         assert_eq!(node_txn[1].input.len(), 2);
4909         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4910         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4911                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4912         } else {
4913                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4914                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4915         }
4916
4917         assert_eq!(node_txn[2].input.len(), 1);
4918         check_spends!(node_txn[2], chan_1.3);
4919
4920         mine_transaction(&nodes[1], &node_txn[1]);
4921         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4922
4923         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4924         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4925         assert_eq!(spend_txn.len(), 1);
4926         assert_eq!(spend_txn[0].input.len(), 1);
4927         check_spends!(spend_txn[0], node_txn[1]);
4928 }
4929
4930 #[test]
4931 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4932         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4933         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4934         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4935         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4936         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4937
4938         // Create some initial channels
4939         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4940
4941         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4942         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4943         assert_eq!(revoked_local_txn[0].input.len(), 1);
4944         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4945
4946         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4947         assert_eq!(revoked_local_txn[0].output.len(), 2);
4948
4949         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4950
4951         // B will generate HTLC-Success from revoked commitment tx
4952         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4953         check_closed_broadcast!(nodes[1], true);
4954         check_added_monitors!(nodes[1], 1);
4955         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4956         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4957
4958         assert_eq!(revoked_htlc_txn.len(), 2);
4959         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4960         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4961         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4962
4963         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4964         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4965         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4966
4967         // A will generate justice tx from B's revoked commitment/HTLC tx
4968         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4969         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4970         check_closed_broadcast!(nodes[0], true);
4971         check_added_monitors!(nodes[0], 1);
4972         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4973
4974         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4975         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4976
4977         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4978         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4979         // transactions next...
4980         assert_eq!(node_txn[0].input.len(), 2);
4981         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4982         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4983                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4984         } else {
4985                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4986                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4987         }
4988
4989         assert_eq!(node_txn[1].input.len(), 1);
4990         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4991
4992         check_spends!(node_txn[2], chan_1.3);
4993
4994         mine_transaction(&nodes[0], &node_txn[1]);
4995         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4996
4997         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4998         // didn't try to generate any new transactions.
4999
5000         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5001         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5002         assert_eq!(spend_txn.len(), 3);
5003         assert_eq!(spend_txn[0].input.len(), 1);
5004         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5005         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5006         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5007         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5008 }
5009
5010 #[test]
5011 fn test_onchain_to_onchain_claim() {
5012         // Test that in case of channel closure, we detect the state of output and claim HTLC
5013         // on downstream peer's remote commitment tx.
5014         // First, have C claim an HTLC against its own latest commitment transaction.
5015         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5016         // channel.
5017         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5018         // gets broadcast.
5019
5020         let chanmon_cfgs = create_chanmon_cfgs(3);
5021         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5022         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5023         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5024
5025         // Create some initial channels
5026         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5027         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5028
5029         // Ensure all nodes are at the same height
5030         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5031         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5032         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5033         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5034
5035         // Rebalance the network a bit by relaying one payment through all the channels ...
5036         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5037         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5038
5039         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5040         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5041         check_spends!(commitment_tx[0], chan_2.3);
5042         nodes[2].node.claim_funds(payment_preimage);
5043         check_added_monitors!(nodes[2], 1);
5044         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5045         assert!(updates.update_add_htlcs.is_empty());
5046         assert!(updates.update_fail_htlcs.is_empty());
5047         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5048         assert!(updates.update_fail_malformed_htlcs.is_empty());
5049
5050         mine_transaction(&nodes[2], &commitment_tx[0]);
5051         check_closed_broadcast!(nodes[2], true);
5052         check_added_monitors!(nodes[2], 1);
5053         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5054
5055         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5056         assert_eq!(c_txn.len(), 3);
5057         assert_eq!(c_txn[0], c_txn[2]);
5058         assert_eq!(commitment_tx[0], c_txn[1]);
5059         check_spends!(c_txn[1], chan_2.3);
5060         check_spends!(c_txn[2], c_txn[1]);
5061         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5062         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5063         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5064         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5065
5066         // 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
5067         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5068         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5069         check_added_monitors!(nodes[1], 1);
5070         let events = nodes[1].node.get_and_clear_pending_events();
5071         assert_eq!(events.len(), 2);
5072         match events[0] {
5073                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5074                 _ => panic!("Unexpected event"),
5075         }
5076         match events[1] {
5077                 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
5078                         assert_eq!(fee_earned_msat, Some(1000));
5079                         assert_eq!(claim_from_onchain_tx, true);
5080                 },
5081                 _ => panic!("Unexpected event"),
5082         }
5083         {
5084                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5085                 // ChannelMonitor: claim tx
5086                 assert_eq!(b_txn.len(), 1);
5087                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5088                 b_txn.clear();
5089         }
5090         check_added_monitors!(nodes[1], 1);
5091         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5092         assert_eq!(msg_events.len(), 3);
5093         match msg_events[0] {
5094                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5095                 _ => panic!("Unexpected event"),
5096         }
5097         match msg_events[1] {
5098                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5099                 _ => panic!("Unexpected event"),
5100         }
5101         match msg_events[2] {
5102                 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, .. } } => {
5103                         assert!(update_add_htlcs.is_empty());
5104                         assert!(update_fail_htlcs.is_empty());
5105                         assert_eq!(update_fulfill_htlcs.len(), 1);
5106                         assert!(update_fail_malformed_htlcs.is_empty());
5107                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5108                 },
5109                 _ => panic!("Unexpected event"),
5110         };
5111         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5112         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5113         mine_transaction(&nodes[1], &commitment_tx[0]);
5114         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5115         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5116         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5117         assert_eq!(b_txn.len(), 3);
5118         check_spends!(b_txn[1], chan_1.3);
5119         check_spends!(b_txn[2], b_txn[1]);
5120         check_spends!(b_txn[0], commitment_tx[0]);
5121         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5122         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5123         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5124
5125         check_closed_broadcast!(nodes[1], true);
5126         check_added_monitors!(nodes[1], 1);
5127 }
5128
5129 #[test]
5130 fn test_duplicate_payment_hash_one_failure_one_success() {
5131         // Topology : A --> B --> C --> D
5132         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5133         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5134         // we forward one of the payments onwards to D.
5135         let chanmon_cfgs = create_chanmon_cfgs(4);
5136         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5137         // When this test was written, the default base fee floated based on the HTLC count.
5138         // It is now fixed, so we simply set the fee to the expected value here.
5139         let mut config = test_default_channel_config();
5140         config.channel_options.forwarding_fee_base_msat = 196;
5141         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5142                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5143         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5144
5145         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5146         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5147         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5148
5149         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5150         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5151         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5152         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5153         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5154
5155         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5156
5157         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, 0).unwrap();
5158         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5159         // script push size limit so that the below script length checks match
5160         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5161         let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph,
5162                 &nodes[3].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 900000, TEST_FINAL_CLTV - 40, nodes[0].logger).unwrap();
5163         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5164
5165         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5166         assert_eq!(commitment_txn[0].input.len(), 1);
5167         check_spends!(commitment_txn[0], chan_2.3);
5168
5169         mine_transaction(&nodes[1], &commitment_txn[0]);
5170         check_closed_broadcast!(nodes[1], true);
5171         check_added_monitors!(nodes[1], 1);
5172         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5173         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5174
5175         let htlc_timeout_tx;
5176         { // Extract one of the two HTLC-Timeout transaction
5177                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5178                 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5179                 assert_eq!(node_txn.len(), 4);
5180                 check_spends!(node_txn[0], chan_2.3);
5181
5182                 check_spends!(node_txn[1], commitment_txn[0]);
5183                 assert_eq!(node_txn[1].input.len(), 1);
5184                 check_spends!(node_txn[2], commitment_txn[0]);
5185                 assert_eq!(node_txn[2].input.len(), 1);
5186                 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5187                 check_spends!(node_txn[3], commitment_txn[0]);
5188                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5189
5190                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5191                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5192                 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5193                 htlc_timeout_tx = node_txn[1].clone();
5194         }
5195
5196         nodes[2].node.claim_funds(our_payment_preimage);
5197         mine_transaction(&nodes[2], &commitment_txn[0]);
5198         check_added_monitors!(nodes[2], 2);
5199         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5200         let events = nodes[2].node.get_and_clear_pending_msg_events();
5201         match events[0] {
5202                 MessageSendEvent::UpdateHTLCs { .. } => {},
5203                 _ => panic!("Unexpected event"),
5204         }
5205         match events[1] {
5206                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5207                 _ => panic!("Unexepected event"),
5208         }
5209         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5210         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)
5211         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5212         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5213         assert_eq!(htlc_success_txn[0].input.len(), 1);
5214         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5215         assert_eq!(htlc_success_txn[1].input.len(), 1);
5216         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5217         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5218         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5219         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5220         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5221         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5222
5223         mine_transaction(&nodes[1], &htlc_timeout_tx);
5224         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5225         expect_pending_htlcs_forwardable!(nodes[1]);
5226         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5227         assert!(htlc_updates.update_add_htlcs.is_empty());
5228         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5229         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5230         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5231         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5232         check_added_monitors!(nodes[1], 1);
5233
5234         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5235         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5236         {
5237                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5238         }
5239         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5240
5241         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5242         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5243         // and nodes[2] fee) is rounded down and then claimed in full.
5244         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5245         expect_payment_forwarded!(nodes[1], Some(196*2), true);
5246         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5247         assert!(updates.update_add_htlcs.is_empty());
5248         assert!(updates.update_fail_htlcs.is_empty());
5249         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5250         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5251         assert!(updates.update_fail_malformed_htlcs.is_empty());
5252         check_added_monitors!(nodes[1], 1);
5253
5254         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5255         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5256
5257         let events = nodes[0].node.get_and_clear_pending_events();
5258         match events[0] {
5259                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
5260                         assert_eq!(*payment_preimage, our_payment_preimage);
5261                         assert_eq!(*payment_hash, duplicate_payment_hash);
5262                 }
5263                 _ => panic!("Unexpected event"),
5264         }
5265 }
5266
5267 #[test]
5268 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5269         let chanmon_cfgs = create_chanmon_cfgs(2);
5270         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5271         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5272         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5273
5274         // Create some initial channels
5275         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5276
5277         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5278         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5279         assert_eq!(local_txn.len(), 1);
5280         assert_eq!(local_txn[0].input.len(), 1);
5281         check_spends!(local_txn[0], chan_1.3);
5282
5283         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5284         nodes[1].node.claim_funds(payment_preimage);
5285         check_added_monitors!(nodes[1], 1);
5286         mine_transaction(&nodes[1], &local_txn[0]);
5287         check_added_monitors!(nodes[1], 1);
5288         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5289         let events = nodes[1].node.get_and_clear_pending_msg_events();
5290         match events[0] {
5291                 MessageSendEvent::UpdateHTLCs { .. } => {},
5292                 _ => panic!("Unexpected event"),
5293         }
5294         match events[1] {
5295                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5296                 _ => panic!("Unexepected event"),
5297         }
5298         let node_tx = {
5299                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5300                 assert_eq!(node_txn.len(), 3);
5301                 assert_eq!(node_txn[0], node_txn[2]);
5302                 assert_eq!(node_txn[1], local_txn[0]);
5303                 assert_eq!(node_txn[0].input.len(), 1);
5304                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5305                 check_spends!(node_txn[0], local_txn[0]);
5306                 node_txn[0].clone()
5307         };
5308
5309         mine_transaction(&nodes[1], &node_tx);
5310         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5311
5312         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5313         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5314         assert_eq!(spend_txn.len(), 1);
5315         assert_eq!(spend_txn[0].input.len(), 1);
5316         check_spends!(spend_txn[0], node_tx);
5317         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5318 }
5319
5320 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5321         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5322         // unrevoked commitment transaction.
5323         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5324         // a remote RAA before they could be failed backwards (and combinations thereof).
5325         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5326         // use the same payment hashes.
5327         // Thus, we use a six-node network:
5328         //
5329         // A \         / E
5330         //    - C - D -
5331         // B /         \ F
5332         // And test where C fails back to A/B when D announces its latest commitment transaction
5333         let chanmon_cfgs = create_chanmon_cfgs(6);
5334         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5335         // When this test was written, the default base fee floated based on the HTLC count.
5336         // It is now fixed, so we simply set the fee to the expected value here.
5337         let mut config = test_default_channel_config();
5338         config.channel_options.forwarding_fee_base_msat = 196;
5339         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5340                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5341         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5342         let logger = test_utils::TestLogger::new();
5343
5344         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5345         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5346         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5347         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5348         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5349
5350         // Rebalance and check output sanity...
5351         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5352         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5353         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5354
5355         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5356         // 0th HTLC:
5357         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
5358         // 1st HTLC:
5359         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
5360         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5361         let our_node_id = &nodes[1].node.get_our_node_id();
5362         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph, &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5363         // 2nd HTLC:
5364         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
5365         // 3rd HTLC:
5366         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
5367         // 4th HTLC:
5368         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5369         // 5th HTLC:
5370         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5371         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph, &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5372         // 6th HTLC:
5373         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());
5374         // 7th HTLC:
5375         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());
5376
5377         // 8th HTLC:
5378         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5379         // 9th HTLC:
5380         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph, &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5381         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
5382
5383         // 10th HTLC:
5384         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
5385         // 11th HTLC:
5386         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph, &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5387         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());
5388
5389         // Double-check that six of the new HTLC were added
5390         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5391         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5392         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5393         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5394
5395         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5396         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5397         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5398         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5399         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5400         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5401         check_added_monitors!(nodes[4], 0);
5402         expect_pending_htlcs_forwardable!(nodes[4]);
5403         check_added_monitors!(nodes[4], 1);
5404
5405         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5406         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5407         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5408         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5409         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5410         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5411
5412         // Fail 3rd below-dust and 7th above-dust HTLCs
5413         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5414         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5415         check_added_monitors!(nodes[5], 0);
5416         expect_pending_htlcs_forwardable!(nodes[5]);
5417         check_added_monitors!(nodes[5], 1);
5418
5419         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5420         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5421         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5422         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5423
5424         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5425
5426         expect_pending_htlcs_forwardable!(nodes[3]);
5427         check_added_monitors!(nodes[3], 1);
5428         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5429         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5430         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5431         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5432         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5433         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5434         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5435         if deliver_last_raa {
5436                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5437         } else {
5438                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5439         }
5440
5441         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5442         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5443         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5444         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5445         //
5446         // We now broadcast the latest commitment transaction, which *should* result in failures for
5447         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5448         // the non-broadcast above-dust HTLCs.
5449         //
5450         // Alternatively, we may broadcast the previous commitment transaction, which should only
5451         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5452         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5453
5454         if announce_latest {
5455                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5456         } else {
5457                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5458         }
5459         let events = nodes[2].node.get_and_clear_pending_events();
5460         let close_event = if deliver_last_raa {
5461                 assert_eq!(events.len(), 2);
5462                 events[1].clone()
5463         } else {
5464                 assert_eq!(events.len(), 1);
5465                 events[0].clone()
5466         };
5467         match close_event {
5468                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5469                 _ => panic!("Unexpected event"),
5470         }
5471
5472         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5473         check_closed_broadcast!(nodes[2], true);
5474         if deliver_last_raa {
5475                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5476         } else {
5477                 expect_pending_htlcs_forwardable!(nodes[2]);
5478         }
5479         check_added_monitors!(nodes[2], 3);
5480
5481         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5482         assert_eq!(cs_msgs.len(), 2);
5483         let mut a_done = false;
5484         for msg in cs_msgs {
5485                 match msg {
5486                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5487                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5488                                 // should be failed-backwards here.
5489                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5490                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5491                                         for htlc in &updates.update_fail_htlcs {
5492                                                 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 });
5493                                         }
5494                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5495                                         assert!(!a_done);
5496                                         a_done = true;
5497                                         &nodes[0]
5498                                 } else {
5499                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5500                                         for htlc in &updates.update_fail_htlcs {
5501                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5502                                         }
5503                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5504                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5505                                         &nodes[1]
5506                                 };
5507                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5508                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5509                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5510                                 if announce_latest {
5511                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5512                                         if *node_id == nodes[0].node.get_our_node_id() {
5513                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5514                                         }
5515                                 }
5516                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5517                         },
5518                         _ => panic!("Unexpected event"),
5519                 }
5520         }
5521
5522         let as_events = nodes[0].node.get_and_clear_pending_events();
5523         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5524         let mut as_failds = HashSet::new();
5525         let mut as_updates = 0;
5526         for event in as_events.iter() {
5527                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5528                         assert!(as_failds.insert(*payment_hash));
5529                         if *payment_hash != payment_hash_2 {
5530                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5531                         } else {
5532                                 assert!(!rejected_by_dest);
5533                         }
5534                         if network_update.is_some() {
5535                                 as_updates += 1;
5536                         }
5537                 } else { panic!("Unexpected event"); }
5538         }
5539         assert!(as_failds.contains(&payment_hash_1));
5540         assert!(as_failds.contains(&payment_hash_2));
5541         if announce_latest {
5542                 assert!(as_failds.contains(&payment_hash_3));
5543                 assert!(as_failds.contains(&payment_hash_5));
5544         }
5545         assert!(as_failds.contains(&payment_hash_6));
5546
5547         let bs_events = nodes[1].node.get_and_clear_pending_events();
5548         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5549         let mut bs_failds = HashSet::new();
5550         let mut bs_updates = 0;
5551         for event in bs_events.iter() {
5552                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5553                         assert!(bs_failds.insert(*payment_hash));
5554                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5555                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5556                         } else {
5557                                 assert!(!rejected_by_dest);
5558                         }
5559                         if network_update.is_some() {
5560                                 bs_updates += 1;
5561                         }
5562                 } else { panic!("Unexpected event"); }
5563         }
5564         assert!(bs_failds.contains(&payment_hash_1));
5565         assert!(bs_failds.contains(&payment_hash_2));
5566         if announce_latest {
5567                 assert!(bs_failds.contains(&payment_hash_4));
5568         }
5569         assert!(bs_failds.contains(&payment_hash_5));
5570
5571         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5572         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5573         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5574         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5575         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5576         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5577 }
5578
5579 #[test]
5580 fn test_fail_backwards_latest_remote_announce_a() {
5581         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5582 }
5583
5584 #[test]
5585 fn test_fail_backwards_latest_remote_announce_b() {
5586         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5587 }
5588
5589 #[test]
5590 fn test_fail_backwards_previous_remote_announce() {
5591         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5592         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5593         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5594 }
5595
5596 #[test]
5597 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5598         let chanmon_cfgs = create_chanmon_cfgs(2);
5599         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5600         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5601         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5602
5603         // Create some initial channels
5604         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5605
5606         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5607         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5608         assert_eq!(local_txn[0].input.len(), 1);
5609         check_spends!(local_txn[0], chan_1.3);
5610
5611         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5612         mine_transaction(&nodes[0], &local_txn[0]);
5613         check_closed_broadcast!(nodes[0], true);
5614         check_added_monitors!(nodes[0], 1);
5615         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5616         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5617
5618         let htlc_timeout = {
5619                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5620                 assert_eq!(node_txn.len(), 2);
5621                 check_spends!(node_txn[0], chan_1.3);
5622                 assert_eq!(node_txn[1].input.len(), 1);
5623                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5624                 check_spends!(node_txn[1], local_txn[0]);
5625                 node_txn[1].clone()
5626         };
5627
5628         mine_transaction(&nodes[0], &htlc_timeout);
5629         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5630         expect_payment_failed!(nodes[0], our_payment_hash, true);
5631
5632         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5633         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5634         assert_eq!(spend_txn.len(), 3);
5635         check_spends!(spend_txn[0], local_txn[0]);
5636         assert_eq!(spend_txn[1].input.len(), 1);
5637         check_spends!(spend_txn[1], htlc_timeout);
5638         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5639         assert_eq!(spend_txn[2].input.len(), 2);
5640         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5641         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5642                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5643 }
5644
5645 #[test]
5646 fn test_key_derivation_params() {
5647         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5648         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5649         // let us re-derive the channel key set to then derive a delayed_payment_key.
5650
5651         let chanmon_cfgs = create_chanmon_cfgs(3);
5652
5653         // We manually create the node configuration to backup the seed.
5654         let seed = [42; 32];
5655         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5656         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);
5657         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() };
5658         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5659         node_cfgs.remove(0);
5660         node_cfgs.insert(0, node);
5661
5662         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5663         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5664
5665         // Create some initial channels
5666         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5667         // for node 0
5668         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5669         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5670         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5671
5672         // Ensure all nodes are at the same height
5673         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5674         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5675         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5676         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5677
5678         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5679         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5680         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5681         assert_eq!(local_txn_1[0].input.len(), 1);
5682         check_spends!(local_txn_1[0], chan_1.3);
5683
5684         // We check funding pubkey are unique
5685         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]));
5686         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]));
5687         if from_0_funding_key_0 == from_1_funding_key_0
5688             || from_0_funding_key_0 == from_1_funding_key_1
5689             || from_0_funding_key_1 == from_1_funding_key_0
5690             || from_0_funding_key_1 == from_1_funding_key_1 {
5691                 panic!("Funding pubkeys aren't unique");
5692         }
5693
5694         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5695         mine_transaction(&nodes[0], &local_txn_1[0]);
5696         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5697         check_closed_broadcast!(nodes[0], true);
5698         check_added_monitors!(nodes[0], 1);
5699         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5700
5701         let htlc_timeout = {
5702                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5703                 assert_eq!(node_txn[1].input.len(), 1);
5704                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5705                 check_spends!(node_txn[1], local_txn_1[0]);
5706                 node_txn[1].clone()
5707         };
5708
5709         mine_transaction(&nodes[0], &htlc_timeout);
5710         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5711         expect_payment_failed!(nodes[0], our_payment_hash, true);
5712
5713         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5714         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5715         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5716         assert_eq!(spend_txn.len(), 3);
5717         check_spends!(spend_txn[0], local_txn_1[0]);
5718         assert_eq!(spend_txn[1].input.len(), 1);
5719         check_spends!(spend_txn[1], htlc_timeout);
5720         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5721         assert_eq!(spend_txn[2].input.len(), 2);
5722         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5723         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5724                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5725 }
5726
5727 #[test]
5728 fn test_static_output_closing_tx() {
5729         let chanmon_cfgs = create_chanmon_cfgs(2);
5730         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5731         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5732         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5733
5734         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5735
5736         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5737         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5738
5739         mine_transaction(&nodes[0], &closing_tx);
5740         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5741         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5742
5743         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5744         assert_eq!(spend_txn.len(), 1);
5745         check_spends!(spend_txn[0], closing_tx);
5746
5747         mine_transaction(&nodes[1], &closing_tx);
5748         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5749         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5750
5751         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5752         assert_eq!(spend_txn.len(), 1);
5753         check_spends!(spend_txn[0], closing_tx);
5754 }
5755
5756 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5757         let chanmon_cfgs = create_chanmon_cfgs(2);
5758         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5759         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5760         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5761         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5762
5763         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5764
5765         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5766         // present in B's local commitment transaction, but none of A's commitment transactions.
5767         assert!(nodes[1].node.claim_funds(our_payment_preimage));
5768         check_added_monitors!(nodes[1], 1);
5769
5770         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5771         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5772         let events = nodes[0].node.get_and_clear_pending_events();
5773         assert_eq!(events.len(), 1);
5774         match events[0] {
5775                 Event::PaymentSent { payment_preimage, payment_hash } => {
5776                         assert_eq!(payment_preimage, our_payment_preimage);
5777                         assert_eq!(payment_hash, our_payment_hash);
5778                 },
5779                 _ => panic!("Unexpected event"),
5780         }
5781
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
5788         let starting_block = nodes[1].best_block_info();
5789         let mut block = Block {
5790                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5791                 txdata: vec![],
5792         };
5793         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5794                 connect_block(&nodes[1], &block);
5795                 block.header.prev_blockhash = block.block_hash();
5796         }
5797         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5798         check_closed_broadcast!(nodes[1], true);
5799         check_added_monitors!(nodes[1], 1);
5800         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5801 }
5802
5803 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5804         let chanmon_cfgs = create_chanmon_cfgs(2);
5805         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5806         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5807         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5808         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5809         let logger = test_utils::TestLogger::new();
5810
5811         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1]);
5812         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5813         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV, &logger).unwrap();
5814         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5815         check_added_monitors!(nodes[0], 1);
5816
5817         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5818
5819         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5820         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5821         // to "time out" the HTLC.
5822
5823         let starting_block = nodes[1].best_block_info();
5824         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5825
5826         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5827                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5828                 header.prev_blockhash = header.block_hash();
5829         }
5830         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5831         check_closed_broadcast!(nodes[0], true);
5832         check_added_monitors!(nodes[0], 1);
5833         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5834 }
5835
5836 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5837         let chanmon_cfgs = create_chanmon_cfgs(3);
5838         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5839         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5840         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5841         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5842
5843         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5844         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5845         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5846         // actually revoked.
5847         let htlc_value = if use_dust { 50000 } else { 3000000 };
5848         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5849         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5850         expect_pending_htlcs_forwardable!(nodes[1]);
5851         check_added_monitors!(nodes[1], 1);
5852
5853         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5854         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5855         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5856         check_added_monitors!(nodes[0], 1);
5857         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5858         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5859         check_added_monitors!(nodes[1], 1);
5860         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5861         check_added_monitors!(nodes[1], 1);
5862         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5863
5864         if check_revoke_no_close {
5865                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5866                 check_added_monitors!(nodes[0], 1);
5867         }
5868
5869         let starting_block = nodes[1].best_block_info();
5870         let mut block = Block {
5871                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5872                 txdata: vec![],
5873         };
5874         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5875                 connect_block(&nodes[0], &block);
5876                 block.header.prev_blockhash = block.block_hash();
5877         }
5878         if !check_revoke_no_close {
5879                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5880                 check_closed_broadcast!(nodes[0], true);
5881                 check_added_monitors!(nodes[0], 1);
5882                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5883         } else {
5884                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5885         }
5886 }
5887
5888 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5889 // There are only a few cases to test here:
5890 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5891 //    broadcastable commitment transactions result in channel closure,
5892 //  * its included in an unrevoked-but-previous remote commitment transaction,
5893 //  * its included in the latest remote or local commitment transactions.
5894 // We test each of the three possible commitment transactions individually and use both dust and
5895 // non-dust HTLCs.
5896 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5897 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5898 // tested for at least one of the cases in other tests.
5899 #[test]
5900 fn htlc_claim_single_commitment_only_a() {
5901         do_htlc_claim_local_commitment_only(true);
5902         do_htlc_claim_local_commitment_only(false);
5903
5904         do_htlc_claim_current_remote_commitment_only(true);
5905         do_htlc_claim_current_remote_commitment_only(false);
5906 }
5907
5908 #[test]
5909 fn htlc_claim_single_commitment_only_b() {
5910         do_htlc_claim_previous_remote_commitment_only(true, false);
5911         do_htlc_claim_previous_remote_commitment_only(false, false);
5912         do_htlc_claim_previous_remote_commitment_only(true, true);
5913         do_htlc_claim_previous_remote_commitment_only(false, true);
5914 }
5915
5916 #[test]
5917 #[should_panic]
5918 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5919         let chanmon_cfgs = create_chanmon_cfgs(2);
5920         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5921         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5922         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5923         //Force duplicate channel ids
5924         for node in nodes.iter() {
5925                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5926         }
5927
5928         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5929         let channel_value_satoshis=10000;
5930         let push_msat=10001;
5931         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5932         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5933         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5934
5935         //Create a second channel with a channel_id collision
5936         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5937 }
5938
5939 #[test]
5940 fn bolt2_open_channel_sending_node_checks_part2() {
5941         let chanmon_cfgs = create_chanmon_cfgs(2);
5942         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5943         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5944         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5945
5946         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5947         let channel_value_satoshis=2^24;
5948         let push_msat=10001;
5949         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5950
5951         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5952         let channel_value_satoshis=10000;
5953         // Test when push_msat is equal to 1000 * funding_satoshis.
5954         let push_msat=1000*channel_value_satoshis+1;
5955         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5956
5957         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5958         let channel_value_satoshis=10000;
5959         let push_msat=10001;
5960         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
5961         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5962         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5963
5964         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5965         // 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
5966         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5967
5968         // 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.
5969         assert!(BREAKDOWN_TIMEOUT>0);
5970         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5971
5972         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5973         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5974         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5975
5976         // 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.
5977         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5978         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5979         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5980         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5981         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5982 }
5983
5984 #[test]
5985 fn bolt2_open_channel_sane_dust_limit() {
5986         let chanmon_cfgs = create_chanmon_cfgs(2);
5987         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5988         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5989         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5990
5991         let channel_value_satoshis=1000000;
5992         let push_msat=10001;
5993         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5994         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5995         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5996         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5997
5998         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5999         let events = nodes[1].node.get_and_clear_pending_msg_events();
6000         let err_msg = match events[0] {
6001                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6002                         msg.clone()
6003                 },
6004                 _ => panic!("Unexpected event"),
6005         };
6006         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6007 }
6008
6009 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6010 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6011 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6012 // is no longer affordable once it's freed.
6013 #[test]
6014 fn test_fail_holding_cell_htlc_upon_free() {
6015         let chanmon_cfgs = create_chanmon_cfgs(2);
6016         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6017         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6018         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6019         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6020         let logger = test_utils::TestLogger::new();
6021
6022         // First nodes[0] generates an update_fee, setting the channel's
6023         // pending_update_fee.
6024         {
6025                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6026                 *feerate_lock += 20;
6027         }
6028         nodes[0].node.timer_tick_occurred();
6029         check_added_monitors!(nodes[0], 1);
6030
6031         let events = nodes[0].node.get_and_clear_pending_msg_events();
6032         assert_eq!(events.len(), 1);
6033         let (update_msg, commitment_signed) = match events[0] {
6034                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6035                         (update_fee.as_ref(), commitment_signed)
6036                 },
6037                 _ => panic!("Unexpected event"),
6038         };
6039
6040         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6041
6042         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6043         let channel_reserve = chan_stat.channel_reserve_msat;
6044         let feerate = get_feerate!(nodes[0], chan.2);
6045
6046         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6047         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6048         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6049         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6050         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6051
6052         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6053         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6054         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6055         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6056
6057         // Flush the pending fee update.
6058         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6059         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6060         check_added_monitors!(nodes[1], 1);
6061         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6062         check_added_monitors!(nodes[0], 1);
6063
6064         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6065         // HTLC, but now that the fee has been raised the payment will now fail, causing
6066         // us to surface its failure to the user.
6067         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6068         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6069         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);
6070         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 {}",
6071                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6072         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6073
6074         // Check that the payment failed to be sent out.
6075         let events = nodes[0].node.get_and_clear_pending_events();
6076         assert_eq!(events.len(), 1);
6077         match &events[0] {
6078                 &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, ref error_code, ref error_data, ref all_paths_failed, path: _ } => {
6079                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6080                         assert_eq!(*rejected_by_dest, false);
6081                         assert_eq!(*all_paths_failed, true);
6082                         assert_eq!(*network_update, None);
6083                         assert_eq!(*error_code, None);
6084                         assert_eq!(*error_data, None);
6085                 },
6086                 _ => panic!("Unexpected event"),
6087         }
6088 }
6089
6090 // Test that if multiple HTLCs are released from the holding cell and one is
6091 // valid but the other is no longer valid upon release, the valid HTLC can be
6092 // successfully completed while the other one fails as expected.
6093 #[test]
6094 fn test_free_and_fail_holding_cell_htlcs() {
6095         let chanmon_cfgs = create_chanmon_cfgs(2);
6096         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6097         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6098         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6099         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6100         let logger = test_utils::TestLogger::new();
6101
6102         // First nodes[0] generates an update_fee, setting the channel's
6103         // pending_update_fee.
6104         {
6105                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6106                 *feerate_lock += 200;
6107         }
6108         nodes[0].node.timer_tick_occurred();
6109         check_added_monitors!(nodes[0], 1);
6110
6111         let events = nodes[0].node.get_and_clear_pending_msg_events();
6112         assert_eq!(events.len(), 1);
6113         let (update_msg, commitment_signed) = match events[0] {
6114                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6115                         (update_fee.as_ref(), commitment_signed)
6116                 },
6117                 _ => panic!("Unexpected event"),
6118         };
6119
6120         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6121
6122         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6123         let channel_reserve = chan_stat.channel_reserve_msat;
6124         let feerate = get_feerate!(nodes[0], chan.2);
6125
6126         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6127         let (payment_preimage_1, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[1]);
6128         let amt_1 = 20000;
6129         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
6130         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6131         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6132         let route_1 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], amt_1, TEST_FINAL_CLTV, &logger).unwrap();
6133         let route_2 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], amt_2, TEST_FINAL_CLTV, &logger).unwrap();
6134
6135         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6136         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6137         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6138         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6139         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6140         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6141         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6142
6143         // Flush the pending fee update.
6144         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6145         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6146         check_added_monitors!(nodes[1], 1);
6147         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6148         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6149         check_added_monitors!(nodes[0], 2);
6150
6151         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6152         // but now that the fee has been raised the second payment will now fail, causing us
6153         // to surface its failure to the user. The first payment should succeed.
6154         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6155         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6156         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);
6157         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 {}",
6158                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6159         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6160
6161         // Check that the second payment failed to be sent out.
6162         let events = nodes[0].node.get_and_clear_pending_events();
6163         assert_eq!(events.len(), 1);
6164         match &events[0] {
6165                 &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, ref error_code, ref error_data, ref all_paths_failed, path: _ } => {
6166                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6167                         assert_eq!(*rejected_by_dest, false);
6168                         assert_eq!(*all_paths_failed, true);
6169                         assert_eq!(*network_update, None);
6170                         assert_eq!(*error_code, None);
6171                         assert_eq!(*error_data, None);
6172                 },
6173                 _ => panic!("Unexpected event"),
6174         }
6175
6176         // Complete the first payment and the RAA from the fee update.
6177         let (payment_event, send_raa_event) = {
6178                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6179                 assert_eq!(msgs.len(), 2);
6180                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6181         };
6182         let raa = match send_raa_event {
6183                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6184                 _ => panic!("Unexpected event"),
6185         };
6186         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6187         check_added_monitors!(nodes[1], 1);
6188         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6189         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6190         let events = nodes[1].node.get_and_clear_pending_events();
6191         assert_eq!(events.len(), 1);
6192         match events[0] {
6193                 Event::PendingHTLCsForwardable { .. } => {},
6194                 _ => panic!("Unexpected event"),
6195         }
6196         nodes[1].node.process_pending_htlc_forwards();
6197         let events = nodes[1].node.get_and_clear_pending_events();
6198         assert_eq!(events.len(), 1);
6199         match events[0] {
6200                 Event::PaymentReceived { .. } => {},
6201                 _ => panic!("Unexpected event"),
6202         }
6203         nodes[1].node.claim_funds(payment_preimage_1);
6204         check_added_monitors!(nodes[1], 1);
6205         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6206         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6207         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6208         let events = nodes[0].node.get_and_clear_pending_events();
6209         assert_eq!(events.len(), 1);
6210         match events[0] {
6211                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
6212                         assert_eq!(*payment_preimage, payment_preimage_1);
6213                         assert_eq!(*payment_hash, payment_hash_1);
6214                 }
6215                 _ => panic!("Unexpected event"),
6216         }
6217 }
6218
6219 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6220 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6221 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6222 // once it's freed.
6223 #[test]
6224 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6225         let chanmon_cfgs = create_chanmon_cfgs(3);
6226         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6227         // When this test was written, the default base fee floated based on the HTLC count.
6228         // It is now fixed, so we simply set the fee to the expected value here.
6229         let mut config = test_default_channel_config();
6230         config.channel_options.forwarding_fee_base_msat = 196;
6231         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6232         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6233         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6234         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6235         let logger = test_utils::TestLogger::new();
6236
6237         // First nodes[1] generates an update_fee, setting the channel's
6238         // pending_update_fee.
6239         {
6240                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6241                 *feerate_lock += 20;
6242         }
6243         nodes[1].node.timer_tick_occurred();
6244         check_added_monitors!(nodes[1], 1);
6245
6246         let events = nodes[1].node.get_and_clear_pending_msg_events();
6247         assert_eq!(events.len(), 1);
6248         let (update_msg, commitment_signed) = match events[0] {
6249                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6250                         (update_fee.as_ref(), commitment_signed)
6251                 },
6252                 _ => panic!("Unexpected event"),
6253         };
6254
6255         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6256
6257         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6258         let channel_reserve = chan_stat.channel_reserve_msat;
6259         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6260
6261         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6262         let feemsat = 239;
6263         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6264         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
6265         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6266         let payment_event = {
6267                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6268                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6269                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6270                 check_added_monitors!(nodes[0], 1);
6271
6272                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6273                 assert_eq!(events.len(), 1);
6274
6275                 SendEvent::from_event(events.remove(0))
6276         };
6277         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6278         check_added_monitors!(nodes[1], 0);
6279         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6280         expect_pending_htlcs_forwardable!(nodes[1]);
6281
6282         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6283         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6284
6285         // Flush the pending fee update.
6286         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6287         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6288         check_added_monitors!(nodes[2], 1);
6289         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6290         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6291         check_added_monitors!(nodes[1], 2);
6292
6293         // A final RAA message is generated to finalize the fee update.
6294         let events = nodes[1].node.get_and_clear_pending_msg_events();
6295         assert_eq!(events.len(), 1);
6296
6297         let raa_msg = match &events[0] {
6298                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6299                         msg.clone()
6300                 },
6301                 _ => panic!("Unexpected event"),
6302         };
6303
6304         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6305         check_added_monitors!(nodes[2], 1);
6306         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6307
6308         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6309         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6310         assert_eq!(process_htlc_forwards_event.len(), 1);
6311         match &process_htlc_forwards_event[0] {
6312                 &Event::PendingHTLCsForwardable { .. } => {},
6313                 _ => panic!("Unexpected event"),
6314         }
6315
6316         // In response, we call ChannelManager's process_pending_htlc_forwards
6317         nodes[1].node.process_pending_htlc_forwards();
6318         check_added_monitors!(nodes[1], 1);
6319
6320         // This causes the HTLC to be failed backwards.
6321         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6322         assert_eq!(fail_event.len(), 1);
6323         let (fail_msg, commitment_signed) = match &fail_event[0] {
6324                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6325                         assert_eq!(updates.update_add_htlcs.len(), 0);
6326                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6327                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6328                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6329                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6330                 },
6331                 _ => panic!("Unexpected event"),
6332         };
6333
6334         // Pass the failure messages back to nodes[0].
6335         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6336         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6337
6338         // Complete the HTLC failure+removal process.
6339         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6340         check_added_monitors!(nodes[0], 1);
6341         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6342         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6343         check_added_monitors!(nodes[1], 2);
6344         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6345         assert_eq!(final_raa_event.len(), 1);
6346         let raa = match &final_raa_event[0] {
6347                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6348                 _ => panic!("Unexpected event"),
6349         };
6350         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6351         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6352         check_added_monitors!(nodes[0], 1);
6353 }
6354
6355 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6356 // 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.
6357 //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.
6358
6359 #[test]
6360 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6361         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6362         let chanmon_cfgs = create_chanmon_cfgs(2);
6363         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6364         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6365         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6366         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6367
6368         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6369         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6370         let logger = test_utils::TestLogger::new();
6371         let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6372         route.paths[0][0].fee_msat = 100;
6373
6374         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6375                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6376         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6377         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6378 }
6379
6380 #[test]
6381 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6382         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6383         let chanmon_cfgs = create_chanmon_cfgs(2);
6384         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6385         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6386         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6387         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6388         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6389
6390         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6391         let logger = test_utils::TestLogger::new();
6392         let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6393         route.paths[0][0].fee_msat = 0;
6394         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6395                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6396
6397         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6398         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6399 }
6400
6401 #[test]
6402 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6403         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6404         let chanmon_cfgs = create_chanmon_cfgs(2);
6405         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6406         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6407         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6408         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6409
6410         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6411         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6412         let logger = test_utils::TestLogger::new();
6413         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6414         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6415         check_added_monitors!(nodes[0], 1);
6416         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6417         updates.update_add_htlcs[0].amount_msat = 0;
6418
6419         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6420         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6421         check_closed_broadcast!(nodes[1], true).unwrap();
6422         check_added_monitors!(nodes[1], 1);
6423         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6424 }
6425
6426 #[test]
6427 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6428         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6429         //It is enforced when constructing a route.
6430         let chanmon_cfgs = create_chanmon_cfgs(2);
6431         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6432         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6433         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6434         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6435         let logger = test_utils::TestLogger::new();
6436
6437         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6438
6439         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6440         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000000, 500000001, &logger).unwrap();
6441         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6442                 assert_eq!(err, &"Channel CLTV overflowed?"));
6443 }
6444
6445 #[test]
6446 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6447         //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.
6448         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6449         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6450         let chanmon_cfgs = create_chanmon_cfgs(2);
6451         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6452         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6453         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6454         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6455         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6456
6457         let logger = test_utils::TestLogger::new();
6458         for i in 0..max_accepted_htlcs {
6459                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6460                 let payment_event = {
6461                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6462                         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6463                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6464                         check_added_monitors!(nodes[0], 1);
6465
6466                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6467                         assert_eq!(events.len(), 1);
6468                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6469                                 assert_eq!(htlcs[0].htlc_id, i);
6470                         } else {
6471                                 assert!(false);
6472                         }
6473                         SendEvent::from_event(events.remove(0))
6474                 };
6475                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6476                 check_added_monitors!(nodes[1], 0);
6477                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6478
6479                 expect_pending_htlcs_forwardable!(nodes[1]);
6480                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6481         }
6482         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6483         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6484         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6485         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6486                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6487
6488         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6489         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6490 }
6491
6492 #[test]
6493 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6494         //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.
6495         let chanmon_cfgs = create_chanmon_cfgs(2);
6496         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6497         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6498         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6499         let channel_value = 100000;
6500         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6501         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6502
6503         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6504
6505         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6506         // Manually create a route over our max in flight (which our router normally automatically
6507         // limits us to.
6508         let route = Route { paths: vec![vec![RouteHop {
6509            pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6510            short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6511            fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6512         }]] };
6513         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6514                 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
6515
6516         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6517         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);
6518
6519         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6520 }
6521
6522 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6523 #[test]
6524 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6525         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6526         let chanmon_cfgs = create_chanmon_cfgs(2);
6527         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6528         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6529         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6530         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6531         let htlc_minimum_msat: u64;
6532         {
6533                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6534                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6535                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6536         }
6537
6538         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6539         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6540         let logger = test_utils::TestLogger::new();
6541         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV, &logger).unwrap();
6542         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6543         check_added_monitors!(nodes[0], 1);
6544         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6545         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6546         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6547         assert!(nodes[1].node.list_channels().is_empty());
6548         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6549         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()));
6550         check_added_monitors!(nodes[1], 1);
6551         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6552 }
6553
6554 #[test]
6555 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6556         //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
6557         let chanmon_cfgs = create_chanmon_cfgs(2);
6558         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6559         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6560         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6561         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6562         let logger = test_utils::TestLogger::new();
6563
6564         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6565         let channel_reserve = chan_stat.channel_reserve_msat;
6566         let feerate = get_feerate!(nodes[0], chan.2);
6567         // The 2* and +1 are for the fee spike reserve.
6568         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6569
6570         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6571         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6572         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6573         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6574         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6575         check_added_monitors!(nodes[0], 1);
6576         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6577
6578         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6579         // at this time channel-initiatee receivers are not required to enforce that senders
6580         // respect the fee_spike_reserve.
6581         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6582         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6583
6584         assert!(nodes[1].node.list_channels().is_empty());
6585         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6586         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6587         check_added_monitors!(nodes[1], 1);
6588         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6589 }
6590
6591 #[test]
6592 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6593         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6594         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6595         let chanmon_cfgs = create_chanmon_cfgs(2);
6596         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6597         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6598         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6599         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6600         let logger = test_utils::TestLogger::new();
6601
6602         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6603         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6604
6605         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6606         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 3999999, TEST_FINAL_CLTV, &logger).unwrap();
6607
6608         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6609         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6610         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6611         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6612
6613         let mut msg = msgs::UpdateAddHTLC {
6614                 channel_id: chan.2,
6615                 htlc_id: 0,
6616                 amount_msat: 1000,
6617                 payment_hash: our_payment_hash,
6618                 cltv_expiry: htlc_cltv,
6619                 onion_routing_packet: onion_packet.clone(),
6620         };
6621
6622         for i in 0..super::channel::OUR_MAX_HTLCS {
6623                 msg.htlc_id = i as u64;
6624                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6625         }
6626         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6627         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6628
6629         assert!(nodes[1].node.list_channels().is_empty());
6630         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6631         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6632         check_added_monitors!(nodes[1], 1);
6633         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6634 }
6635
6636 #[test]
6637 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6638         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6639         let chanmon_cfgs = create_chanmon_cfgs(2);
6640         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6641         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6642         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6643         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6644         let logger = test_utils::TestLogger::new();
6645
6646         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6647         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6648         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6649         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6650         check_added_monitors!(nodes[0], 1);
6651         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6652         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6653         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6654
6655         assert!(nodes[1].node.list_channels().is_empty());
6656         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6657         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6658         check_added_monitors!(nodes[1], 1);
6659         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6660 }
6661
6662 #[test]
6663 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6664         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6665         let chanmon_cfgs = create_chanmon_cfgs(2);
6666         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6667         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6668         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6669         let logger = test_utils::TestLogger::new();
6670
6671         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6672         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6673         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6674         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6675         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6676         check_added_monitors!(nodes[0], 1);
6677         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6678         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6679         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6680
6681         assert!(nodes[1].node.list_channels().is_empty());
6682         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6683         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6684         check_added_monitors!(nodes[1], 1);
6685         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6686 }
6687
6688 #[test]
6689 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6690         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6691         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6692         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6693         let chanmon_cfgs = create_chanmon_cfgs(2);
6694         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6695         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6696         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6697         let logger = test_utils::TestLogger::new();
6698
6699         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6700         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6701         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6702         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6703         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6704         check_added_monitors!(nodes[0], 1);
6705         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6706         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6707
6708         //Disconnect and Reconnect
6709         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6710         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6711         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6712         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6713         assert_eq!(reestablish_1.len(), 1);
6714         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6715         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6716         assert_eq!(reestablish_2.len(), 1);
6717         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6718         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6719         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6720         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6721
6722         //Resend HTLC
6723         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6724         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6725         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6726         check_added_monitors!(nodes[1], 1);
6727         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6728
6729         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6730
6731         assert!(nodes[1].node.list_channels().is_empty());
6732         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6733         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6734         check_added_monitors!(nodes[1], 1);
6735         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6736 }
6737
6738 #[test]
6739 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6740         //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.
6741
6742         let chanmon_cfgs = create_chanmon_cfgs(2);
6743         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6744         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6745         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6746         let logger = test_utils::TestLogger::new();
6747         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6748         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6749         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6750         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6751         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6752
6753         check_added_monitors!(nodes[0], 1);
6754         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6755         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6756
6757         let update_msg = msgs::UpdateFulfillHTLC{
6758                 channel_id: chan.2,
6759                 htlc_id: 0,
6760                 payment_preimage: our_payment_preimage,
6761         };
6762
6763         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6764
6765         assert!(nodes[0].node.list_channels().is_empty());
6766         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6767         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()));
6768         check_added_monitors!(nodes[0], 1);
6769         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6770 }
6771
6772 #[test]
6773 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6774         //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.
6775
6776         let chanmon_cfgs = create_chanmon_cfgs(2);
6777         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6778         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6779         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6780         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6781         let logger = test_utils::TestLogger::new();
6782
6783         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6784         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6785         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6786         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6787         check_added_monitors!(nodes[0], 1);
6788         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6789         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6790
6791         let update_msg = msgs::UpdateFailHTLC{
6792                 channel_id: chan.2,
6793                 htlc_id: 0,
6794                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6795         };
6796
6797         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6798
6799         assert!(nodes[0].node.list_channels().is_empty());
6800         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6801         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()));
6802         check_added_monitors!(nodes[0], 1);
6803         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6804 }
6805
6806 #[test]
6807 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6808         //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.
6809
6810         let chanmon_cfgs = create_chanmon_cfgs(2);
6811         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6812         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6813         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6814         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6815         let logger = test_utils::TestLogger::new();
6816
6817         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6818         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6819         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6820         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6821         check_added_monitors!(nodes[0], 1);
6822         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6823         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6824         let update_msg = msgs::UpdateFailMalformedHTLC{
6825                 channel_id: chan.2,
6826                 htlc_id: 0,
6827                 sha256_of_onion: [1; 32],
6828                 failure_code: 0x8000,
6829         };
6830
6831         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6832
6833         assert!(nodes[0].node.list_channels().is_empty());
6834         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6835         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()));
6836         check_added_monitors!(nodes[0], 1);
6837         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6838 }
6839
6840 #[test]
6841 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6842         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6843
6844         let chanmon_cfgs = create_chanmon_cfgs(2);
6845         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6846         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6847         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6848         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6849
6850         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6851
6852         nodes[1].node.claim_funds(our_payment_preimage);
6853         check_added_monitors!(nodes[1], 1);
6854
6855         let events = nodes[1].node.get_and_clear_pending_msg_events();
6856         assert_eq!(events.len(), 1);
6857         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6858                 match events[0] {
6859                         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, .. } } => {
6860                                 assert!(update_add_htlcs.is_empty());
6861                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6862                                 assert!(update_fail_htlcs.is_empty());
6863                                 assert!(update_fail_malformed_htlcs.is_empty());
6864                                 assert!(update_fee.is_none());
6865                                 update_fulfill_htlcs[0].clone()
6866                         },
6867                         _ => panic!("Unexpected event"),
6868                 }
6869         };
6870
6871         update_fulfill_msg.htlc_id = 1;
6872
6873         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6874
6875         assert!(nodes[0].node.list_channels().is_empty());
6876         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6877         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6878         check_added_monitors!(nodes[0], 1);
6879         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6880 }
6881
6882 #[test]
6883 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6884         //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.
6885
6886         let chanmon_cfgs = create_chanmon_cfgs(2);
6887         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6888         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6889         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6890         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6891
6892         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6893
6894         nodes[1].node.claim_funds(our_payment_preimage);
6895         check_added_monitors!(nodes[1], 1);
6896
6897         let events = nodes[1].node.get_and_clear_pending_msg_events();
6898         assert_eq!(events.len(), 1);
6899         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6900                 match events[0] {
6901                         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, .. } } => {
6902                                 assert!(update_add_htlcs.is_empty());
6903                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6904                                 assert!(update_fail_htlcs.is_empty());
6905                                 assert!(update_fail_malformed_htlcs.is_empty());
6906                                 assert!(update_fee.is_none());
6907                                 update_fulfill_htlcs[0].clone()
6908                         },
6909                         _ => panic!("Unexpected event"),
6910                 }
6911         };
6912
6913         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6914
6915         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6916
6917         assert!(nodes[0].node.list_channels().is_empty());
6918         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6919         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6920         check_added_monitors!(nodes[0], 1);
6921         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6922 }
6923
6924 #[test]
6925 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6926         //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.
6927
6928         let chanmon_cfgs = create_chanmon_cfgs(2);
6929         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6930         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6931         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6932         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6933         let logger = test_utils::TestLogger::new();
6934
6935         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6936         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6937         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6938         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6939         check_added_monitors!(nodes[0], 1);
6940
6941         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6942         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6943
6944         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6945         check_added_monitors!(nodes[1], 0);
6946         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6947
6948         let events = nodes[1].node.get_and_clear_pending_msg_events();
6949
6950         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6951                 match events[0] {
6952                         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, .. } } => {
6953                                 assert!(update_add_htlcs.is_empty());
6954                                 assert!(update_fulfill_htlcs.is_empty());
6955                                 assert!(update_fail_htlcs.is_empty());
6956                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6957                                 assert!(update_fee.is_none());
6958                                 update_fail_malformed_htlcs[0].clone()
6959                         },
6960                         _ => panic!("Unexpected event"),
6961                 }
6962         };
6963         update_msg.failure_code &= !0x8000;
6964         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6965
6966         assert!(nodes[0].node.list_channels().is_empty());
6967         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6968         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6969         check_added_monitors!(nodes[0], 1);
6970         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6971 }
6972
6973 #[test]
6974 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6975         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6976         //    * 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.
6977
6978         let chanmon_cfgs = create_chanmon_cfgs(3);
6979         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6980         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6981         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6982         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6983         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6984         let logger = test_utils::TestLogger::new();
6985
6986         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
6987
6988         //First hop
6989         let mut payment_event = {
6990                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6991                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
6992                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6993                 check_added_monitors!(nodes[0], 1);
6994                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6995                 assert_eq!(events.len(), 1);
6996                 SendEvent::from_event(events.remove(0))
6997         };
6998         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6999         check_added_monitors!(nodes[1], 0);
7000         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7001         expect_pending_htlcs_forwardable!(nodes[1]);
7002         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7003         assert_eq!(events_2.len(), 1);
7004         check_added_monitors!(nodes[1], 1);
7005         payment_event = SendEvent::from_event(events_2.remove(0));
7006         assert_eq!(payment_event.msgs.len(), 1);
7007
7008         //Second Hop
7009         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7010         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7011         check_added_monitors!(nodes[2], 0);
7012         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7013
7014         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7015         assert_eq!(events_3.len(), 1);
7016         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7017                 match events_3[0] {
7018                         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 } } => {
7019                                 assert!(update_add_htlcs.is_empty());
7020                                 assert!(update_fulfill_htlcs.is_empty());
7021                                 assert!(update_fail_htlcs.is_empty());
7022                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7023                                 assert!(update_fee.is_none());
7024                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7025                         },
7026                         _ => panic!("Unexpected event"),
7027                 }
7028         };
7029
7030         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7031
7032         check_added_monitors!(nodes[1], 0);
7033         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7034         expect_pending_htlcs_forwardable!(nodes[1]);
7035         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7036         assert_eq!(events_4.len(), 1);
7037
7038         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7039         match events_4[0] {
7040                 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, .. } } => {
7041                         assert!(update_add_htlcs.is_empty());
7042                         assert!(update_fulfill_htlcs.is_empty());
7043                         assert_eq!(update_fail_htlcs.len(), 1);
7044                         assert!(update_fail_malformed_htlcs.is_empty());
7045                         assert!(update_fee.is_none());
7046                 },
7047                 _ => panic!("Unexpected event"),
7048         };
7049
7050         check_added_monitors!(nodes[1], 1);
7051 }
7052
7053 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7054         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7055         // 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
7056         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7057
7058         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7059         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7060         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7061         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7062         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7063         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7064
7065         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7066
7067         // We route 2 dust-HTLCs between A and B
7068         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7069         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7070         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7071
7072         // Cache one local commitment tx as previous
7073         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7074
7075         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7076         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7077         check_added_monitors!(nodes[1], 0);
7078         expect_pending_htlcs_forwardable!(nodes[1]);
7079         check_added_monitors!(nodes[1], 1);
7080
7081         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7082         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7083         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7084         check_added_monitors!(nodes[0], 1);
7085
7086         // Cache one local commitment tx as lastest
7087         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7088
7089         let events = nodes[0].node.get_and_clear_pending_msg_events();
7090         match events[0] {
7091                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7092                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7093                 },
7094                 _ => panic!("Unexpected event"),
7095         }
7096         match events[1] {
7097                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7098                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7099                 },
7100                 _ => panic!("Unexpected event"),
7101         }
7102
7103         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7104         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7105         if announce_latest {
7106                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7107         } else {
7108                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7109         }
7110
7111         check_closed_broadcast!(nodes[0], true);
7112         check_added_monitors!(nodes[0], 1);
7113         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7114
7115         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7116         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7117         let events = nodes[0].node.get_and_clear_pending_events();
7118         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7119         assert_eq!(events.len(), 2);
7120         let mut first_failed = false;
7121         for event in events {
7122                 match event {
7123                         Event::PaymentPathFailed { payment_hash, .. } => {
7124                                 if payment_hash == payment_hash_1 {
7125                                         assert!(!first_failed);
7126                                         first_failed = true;
7127                                 } else {
7128                                         assert_eq!(payment_hash, payment_hash_2);
7129                                 }
7130                         }
7131                         _ => panic!("Unexpected event"),
7132                 }
7133         }
7134 }
7135
7136 #[test]
7137 fn test_failure_delay_dust_htlc_local_commitment() {
7138         do_test_failure_delay_dust_htlc_local_commitment(true);
7139         do_test_failure_delay_dust_htlc_local_commitment(false);
7140 }
7141
7142 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7143         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7144         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7145         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7146         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7147         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7148         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7149
7150         let chanmon_cfgs = create_chanmon_cfgs(3);
7151         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7152         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7153         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7154         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7155
7156         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7157
7158         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7159         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7160
7161         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7162         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7163
7164         // We revoked bs_commitment_tx
7165         if revoked {
7166                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7167                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7168         }
7169
7170         let mut timeout_tx = Vec::new();
7171         if local {
7172                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7173                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7174                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7175                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7176                 expect_payment_failed!(nodes[0], dust_hash, true);
7177
7178                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7179                 check_closed_broadcast!(nodes[0], true);
7180                 check_added_monitors!(nodes[0], 1);
7181                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7182                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7183                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7184                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7185                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7186                 mine_transaction(&nodes[0], &timeout_tx[0]);
7187                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7188                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7189         } else {
7190                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7191                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7192                 check_closed_broadcast!(nodes[0], true);
7193                 check_added_monitors!(nodes[0], 1);
7194                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7195                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7196                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7197                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7198                 if !revoked {
7199                         expect_payment_failed!(nodes[0], dust_hash, true);
7200                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7201                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7202                         mine_transaction(&nodes[0], &timeout_tx[0]);
7203                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7204                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7205                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7206                 } else {
7207                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7208                         // commitment tx
7209                         let events = nodes[0].node.get_and_clear_pending_events();
7210                         assert_eq!(events.len(), 2);
7211                         let first;
7212                         match events[0] {
7213                                 Event::PaymentPathFailed { payment_hash, .. } => {
7214                                         if payment_hash == dust_hash { first = true; }
7215                                         else { first = false; }
7216                                 },
7217                                 _ => panic!("Unexpected event"),
7218                         }
7219                         match events[1] {
7220                                 Event::PaymentPathFailed { payment_hash, .. } => {
7221                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7222                                         else { assert_eq!(payment_hash, dust_hash); }
7223                                 },
7224                                 _ => panic!("Unexpected event"),
7225                         }
7226                 }
7227         }
7228 }
7229
7230 #[test]
7231 fn test_sweep_outbound_htlc_failure_update() {
7232         do_test_sweep_outbound_htlc_failure_update(false, true);
7233         do_test_sweep_outbound_htlc_failure_update(false, false);
7234         do_test_sweep_outbound_htlc_failure_update(true, false);
7235 }
7236
7237 #[test]
7238 fn test_user_configurable_csv_delay() {
7239         // We test our channel constructors yield errors when we pass them absurd csv delay
7240
7241         let mut low_our_to_self_config = UserConfig::default();
7242         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7243         let mut high_their_to_self_config = UserConfig::default();
7244         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7245         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7246         let chanmon_cfgs = create_chanmon_cfgs(2);
7247         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7248         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7249         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7250
7251         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7252         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) {
7253                 match error {
7254                         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())); },
7255                         _ => panic!("Unexpected event"),
7256                 }
7257         } else { assert!(false) }
7258
7259         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7260         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7261         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7262         open_channel.to_self_delay = 200;
7263         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) {
7264                 match error {
7265                         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()));  },
7266                         _ => panic!("Unexpected event"),
7267                 }
7268         } else { assert!(false); }
7269
7270         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7271         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7272         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()));
7273         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7274         accept_channel.to_self_delay = 200;
7275         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7276         let reason_msg;
7277         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7278                 match action {
7279                         &ErrorAction::SendErrorMessage { ref msg } => {
7280                                 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()));
7281                                 reason_msg = msg.data.clone();
7282                         },
7283                         _ => { panic!(); }
7284                 }
7285         } else { panic!(); }
7286         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7287
7288         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7289         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7290         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7291         open_channel.to_self_delay = 200;
7292         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) {
7293                 match error {
7294                         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())); },
7295                         _ => panic!("Unexpected event"),
7296                 }
7297         } else { assert!(false); }
7298 }
7299
7300 #[test]
7301 fn test_data_loss_protect() {
7302         // We want to be sure that :
7303         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7304         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7305         // * we close channel in case of detecting other being fallen behind
7306         // * we are able to claim our own outputs thanks to to_remote being static
7307         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7308         let persister;
7309         let logger;
7310         let fee_estimator;
7311         let tx_broadcaster;
7312         let chain_source;
7313         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7314         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7315         // during signing due to revoked tx
7316         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7317         let keys_manager = &chanmon_cfgs[0].keys_manager;
7318         let monitor;
7319         let node_state_0;
7320         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7321         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7322         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7323
7324         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7325
7326         // Cache node A state before any channel update
7327         let previous_node_state = nodes[0].node.encode();
7328         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7329         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7330
7331         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7332         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7333
7334         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7335         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7336
7337         // Restore node A from previous state
7338         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7339         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7340         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7341         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7342         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7343         persister = test_utils::TestPersister::new();
7344         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7345         node_state_0 = {
7346                 let mut channel_monitors = HashMap::new();
7347                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7348                 <(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 {
7349                         keys_manager: keys_manager,
7350                         fee_estimator: &fee_estimator,
7351                         chain_monitor: &monitor,
7352                         logger: &logger,
7353                         tx_broadcaster: &tx_broadcaster,
7354                         default_config: UserConfig::default(),
7355                         channel_monitors,
7356                 }).unwrap().1
7357         };
7358         nodes[0].node = &node_state_0;
7359         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7360         nodes[0].chain_monitor = &monitor;
7361         nodes[0].chain_source = &chain_source;
7362
7363         check_added_monitors!(nodes[0], 1);
7364
7365         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7366         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7367
7368         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7369
7370         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7371         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7372         check_added_monitors!(nodes[0], 1);
7373
7374         {
7375                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7376                 assert_eq!(node_txn.len(), 0);
7377         }
7378
7379         let mut reestablish_1 = Vec::with_capacity(1);
7380         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7381                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7382                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7383                         reestablish_1.push(msg.clone());
7384                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7385                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7386                         match action {
7387                                 &ErrorAction::SendErrorMessage { ref msg } => {
7388                                         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");
7389                                 },
7390                                 _ => panic!("Unexpected event!"),
7391                         }
7392                 } else {
7393                         panic!("Unexpected event")
7394                 }
7395         }
7396
7397         // Check we close channel detecting A is fallen-behind
7398         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7399         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7400         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7401         check_added_monitors!(nodes[1], 1);
7402
7403         // Check A is able to claim to_remote output
7404         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7405         assert_eq!(node_txn.len(), 1);
7406         check_spends!(node_txn[0], chan.3);
7407         assert_eq!(node_txn[0].output.len(), 2);
7408         mine_transaction(&nodes[0], &node_txn[0]);
7409         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7410         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() });
7411         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7412         assert_eq!(spend_txn.len(), 1);
7413         check_spends!(spend_txn[0], node_txn[0]);
7414 }
7415
7416 #[test]
7417 fn test_check_htlc_underpaying() {
7418         // Send payment through A -> B but A is maliciously
7419         // sending a probe payment (i.e less than expected value0
7420         // to B, B should refuse payment.
7421
7422         let chanmon_cfgs = create_chanmon_cfgs(2);
7423         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7424         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7425         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7426
7427         // Create some initial channels
7428         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7429
7430         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();
7431         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7432         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, 0).unwrap();
7433         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7434         check_added_monitors!(nodes[0], 1);
7435
7436         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7437         assert_eq!(events.len(), 1);
7438         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7439         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7440         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7441
7442         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7443         // and then will wait a second random delay before failing the HTLC back:
7444         expect_pending_htlcs_forwardable!(nodes[1]);
7445         expect_pending_htlcs_forwardable!(nodes[1]);
7446
7447         // Node 3 is expecting payment of 100_000 but received 10_000,
7448         // it should fail htlc like we didn't know the preimage.
7449         nodes[1].node.process_pending_htlc_forwards();
7450
7451         let events = nodes[1].node.get_and_clear_pending_msg_events();
7452         assert_eq!(events.len(), 1);
7453         let (update_fail_htlc, commitment_signed) = match events[0] {
7454                 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 } } => {
7455                         assert!(update_add_htlcs.is_empty());
7456                         assert!(update_fulfill_htlcs.is_empty());
7457                         assert_eq!(update_fail_htlcs.len(), 1);
7458                         assert!(update_fail_malformed_htlcs.is_empty());
7459                         assert!(update_fee.is_none());
7460                         (update_fail_htlcs[0].clone(), commitment_signed)
7461                 },
7462                 _ => panic!("Unexpected event"),
7463         };
7464         check_added_monitors!(nodes[1], 1);
7465
7466         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7467         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7468
7469         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7470         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7471         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7472         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7473 }
7474
7475 #[test]
7476 fn test_announce_disable_channels() {
7477         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7478         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7479
7480         let chanmon_cfgs = create_chanmon_cfgs(2);
7481         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7482         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7483         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7484
7485         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7486         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7487         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7488
7489         // Disconnect peers
7490         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7491         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7492
7493         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7494         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7495         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7496         assert_eq!(msg_events.len(), 3);
7497         let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7498         for e in msg_events {
7499                 match e {
7500                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7501                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7502                                 // Check that each channel gets updated exactly once
7503                                 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7504                                         panic!("Generated ChannelUpdate for wrong chan!");
7505                                 }
7506                         },
7507                         _ => panic!("Unexpected event"),
7508                 }
7509         }
7510         // Reconnect peers
7511         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7512         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7513         assert_eq!(reestablish_1.len(), 3);
7514         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7515         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7516         assert_eq!(reestablish_2.len(), 3);
7517
7518         // Reestablish chan_1
7519         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7520         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7521         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7522         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7523         // Reestablish chan_2
7524         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7525         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7526         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7527         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7528         // Reestablish chan_3
7529         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7530         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7531         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7532         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7533
7534         nodes[0].node.timer_tick_occurred();
7535         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7536         nodes[0].node.timer_tick_occurred();
7537         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7538         assert_eq!(msg_events.len(), 3);
7539         chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7540         for e in msg_events {
7541                 match e {
7542                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7543                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7544                                 // Check that each channel gets updated exactly once
7545                                 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7546                                         panic!("Generated ChannelUpdate for wrong chan!");
7547                                 }
7548                         },
7549                         _ => panic!("Unexpected event"),
7550                 }
7551         }
7552 }
7553
7554 #[test]
7555 fn test_priv_forwarding_rejection() {
7556         // If we have a private channel with outbound liquidity, and
7557         // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7558         // to forward through that channel.
7559         let chanmon_cfgs = create_chanmon_cfgs(3);
7560         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7561         let mut no_announce_cfg = test_default_channel_config();
7562         no_announce_cfg.channel_options.announced_channel = false;
7563         no_announce_cfg.accept_forwards_to_priv_channels = false;
7564         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7565         let persister: test_utils::TestPersister;
7566         let new_chain_monitor: test_utils::TestChainMonitor;
7567         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7568         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7569
7570         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
7571
7572         // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7573         // not send for private channels.
7574         nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7575         let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7576         nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7577         let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7578         nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7579
7580         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7581         nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7582         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()));
7583         check_added_monitors!(nodes[2], 1);
7584
7585         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()));
7586         check_added_monitors!(nodes[1], 1);
7587
7588         let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7589         confirm_transaction_at(&nodes[1], &tx, conf_height);
7590         connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7591         confirm_transaction_at(&nodes[2], &tx, conf_height);
7592         connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7593         let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7594         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()));
7595         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7596         nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7597         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7598
7599         assert!(nodes[0].node.list_usable_channels()[0].is_public);
7600         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7601         assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7602
7603         // We should always be able to forward through nodes[1] as long as its out through a public
7604         // channel:
7605         send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7606
7607         // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7608         // to nodes[2], which should be rejected:
7609         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
7610         let route = get_route(&nodes[0].node.get_our_node_id(),
7611                 &nodes[0].net_graph_msg_handler.network_graph,
7612                 &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None,
7613                 &[&RouteHint(vec![RouteHintHop {
7614                         src_node_id: nodes[1].node.get_our_node_id(),
7615                         short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7616                         fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7617                         cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7618                         htlc_minimum_msat: None,
7619                         htlc_maximum_msat: None,
7620                 }])], 10_000, TEST_FINAL_CLTV, nodes[0].logger).unwrap();
7621
7622         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7623         check_added_monitors!(nodes[0], 1);
7624         let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7625         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7626         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7627
7628         let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7629         assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7630         assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7631         assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7632         assert!(htlc_fail_updates.update_fee.is_none());
7633
7634         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7635         commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7636         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7637
7638         // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7639         // to true. Sadly there is currently no way to change it at runtime.
7640
7641         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7642         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7643
7644         let nodes_1_serialized = nodes[1].node.encode();
7645         let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7646         let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7647         {
7648                 let mons = nodes[1].chain_monitor.chain_monitor.monitors.read().unwrap();
7649                 let mut mon_iter = mons.iter();
7650                 mon_iter.next().unwrap().1.write(&mut monitor_a_serialized).unwrap();
7651                 mon_iter.next().unwrap().1.write(&mut monitor_b_serialized).unwrap();
7652         }
7653
7654         persister = test_utils::TestPersister::new();
7655         let keys_manager = &chanmon_cfgs[1].keys_manager;
7656         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);
7657         nodes[1].chain_monitor = &new_chain_monitor;
7658
7659         let mut monitor_a_read = &monitor_a_serialized.0[..];
7660         let mut monitor_b_read = &monitor_b_serialized.0[..];
7661         let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7662         let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7663         assert!(monitor_a_read.is_empty());
7664         assert!(monitor_b_read.is_empty());
7665
7666         no_announce_cfg.accept_forwards_to_priv_channels = true;
7667
7668         let mut nodes_1_read = &nodes_1_serialized[..];
7669         let (_, nodes_1_deserialized_tmp) = {
7670                 let mut channel_monitors = HashMap::new();
7671                 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7672                 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7673                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7674                         default_config: no_announce_cfg,
7675                         keys_manager,
7676                         fee_estimator: node_cfgs[1].fee_estimator,
7677                         chain_monitor: nodes[1].chain_monitor,
7678                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7679                         logger: nodes[1].logger,
7680                         channel_monitors,
7681                 }).unwrap()
7682         };
7683         assert!(nodes_1_read.is_empty());
7684         nodes_1_deserialized = nodes_1_deserialized_tmp;
7685
7686         assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7687         assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7688         check_added_monitors!(nodes[1], 2);
7689         nodes[1].node = &nodes_1_deserialized;
7690
7691         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7692         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7693         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7694         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7695         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7696         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7697         get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7698         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7699
7700         nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7701         nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7702         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7703         let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7704         nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7705         nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7706         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7707         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7708
7709         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7710         check_added_monitors!(nodes[0], 1);
7711         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7712         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7713 }
7714
7715 #[test]
7716 fn test_bump_penalty_txn_on_revoked_commitment() {
7717         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7718         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7719
7720         let chanmon_cfgs = create_chanmon_cfgs(2);
7721         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7722         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7723         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7724
7725         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7726         let logger = test_utils::TestLogger::new();
7727
7728         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7729         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7730         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3000000, 30, &logger).unwrap();
7731         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7732
7733         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7734         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7735         assert_eq!(revoked_txn[0].output.len(), 4);
7736         assert_eq!(revoked_txn[0].input.len(), 1);
7737         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7738         let revoked_txid = revoked_txn[0].txid();
7739
7740         let mut penalty_sum = 0;
7741         for outp in revoked_txn[0].output.iter() {
7742                 if outp.script_pubkey.is_v0_p2wsh() {
7743                         penalty_sum += outp.value;
7744                 }
7745         }
7746
7747         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7748         let header_114 = connect_blocks(&nodes[1], 14);
7749
7750         // Actually revoke tx by claiming a HTLC
7751         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7752         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7753         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7754         check_added_monitors!(nodes[1], 1);
7755
7756         // One or more justice tx should have been broadcast, check it
7757         let penalty_1;
7758         let feerate_1;
7759         {
7760                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7761                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7762                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7763                 assert_eq!(node_txn[0].output.len(), 1);
7764                 check_spends!(node_txn[0], revoked_txn[0]);
7765                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7766                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7767                 penalty_1 = node_txn[0].txid();
7768                 node_txn.clear();
7769         };
7770
7771         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7772         connect_blocks(&nodes[1], 15);
7773         let mut penalty_2 = penalty_1;
7774         let mut feerate_2 = 0;
7775         {
7776                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7777                 assert_eq!(node_txn.len(), 1);
7778                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7779                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7780                         assert_eq!(node_txn[0].output.len(), 1);
7781                         check_spends!(node_txn[0], revoked_txn[0]);
7782                         penalty_2 = node_txn[0].txid();
7783                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7784                         assert_ne!(penalty_2, penalty_1);
7785                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7786                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7787                         // Verify 25% bump heuristic
7788                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7789                         node_txn.clear();
7790                 }
7791         }
7792         assert_ne!(feerate_2, 0);
7793
7794         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7795         connect_blocks(&nodes[1], 1);
7796         let penalty_3;
7797         let mut feerate_3 = 0;
7798         {
7799                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7800                 assert_eq!(node_txn.len(), 1);
7801                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7802                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7803                         assert_eq!(node_txn[0].output.len(), 1);
7804                         check_spends!(node_txn[0], revoked_txn[0]);
7805                         penalty_3 = node_txn[0].txid();
7806                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7807                         assert_ne!(penalty_3, penalty_2);
7808                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7809                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7810                         // Verify 25% bump heuristic
7811                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7812                         node_txn.clear();
7813                 }
7814         }
7815         assert_ne!(feerate_3, 0);
7816
7817         nodes[1].node.get_and_clear_pending_events();
7818         nodes[1].node.get_and_clear_pending_msg_events();
7819 }
7820
7821 #[test]
7822 fn test_bump_penalty_txn_on_revoked_htlcs() {
7823         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7824         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7825
7826         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7827         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7828         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7829         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7830         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7831
7832         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7833         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7834         let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph,
7835                 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7836         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7837         let route = get_route(&nodes[1].node.get_our_node_id(), &nodes[1].net_graph_msg_handler.network_graph,
7838                 &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7839         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7840
7841         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7842         assert_eq!(revoked_local_txn[0].input.len(), 1);
7843         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7844
7845         // Revoke local commitment tx
7846         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7847
7848         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7849         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7850         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7851         check_closed_broadcast!(nodes[1], true);
7852         check_added_monitors!(nodes[1], 1);
7853         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7854         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7855
7856         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7857         assert_eq!(revoked_htlc_txn.len(), 3);
7858         check_spends!(revoked_htlc_txn[1], chan.3);
7859
7860         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7861         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7862         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7863
7864         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7865         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7866         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7867         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7868
7869         // Broadcast set of revoked txn on A
7870         let hash_128 = connect_blocks(&nodes[0], 40);
7871         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7872         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7873         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7874         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7875         let events = nodes[0].node.get_and_clear_pending_events();
7876         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7877         match events[1] {
7878                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7879                 _ => panic!("Unexpected event"),
7880         }
7881         let first;
7882         let feerate_1;
7883         let penalty_txn;
7884         {
7885                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7886                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7887                 // Verify claim tx are spending revoked HTLC txn
7888
7889                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7890                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7891                 // which are included in the same block (they are broadcasted because we scan the
7892                 // transactions linearly and generate claims as we go, they likely should be removed in the
7893                 // future).
7894                 assert_eq!(node_txn[0].input.len(), 1);
7895                 check_spends!(node_txn[0], revoked_local_txn[0]);
7896                 assert_eq!(node_txn[1].input.len(), 1);
7897                 check_spends!(node_txn[1], revoked_local_txn[0]);
7898                 assert_eq!(node_txn[2].input.len(), 1);
7899                 check_spends!(node_txn[2], revoked_local_txn[0]);
7900
7901                 // Each of the three justice transactions claim a separate (single) output of the three
7902                 // available, which we check here:
7903                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7904                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7905                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7906
7907                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7908                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7909
7910                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7911                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7912                 // a remote commitment tx has already been confirmed).
7913                 check_spends!(node_txn[3], chan.3);
7914
7915                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7916                 // output, checked above).
7917                 assert_eq!(node_txn[4].input.len(), 2);
7918                 assert_eq!(node_txn[4].output.len(), 1);
7919                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7920
7921                 first = node_txn[4].txid();
7922                 // Store both feerates for later comparison
7923                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7924                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7925                 penalty_txn = vec![node_txn[2].clone()];
7926                 node_txn.clear();
7927         }
7928
7929         // Connect one more block to see if bumped penalty are issued for HTLC txn
7930         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7931         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7932         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7933         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7934         {
7935                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7936                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7937
7938                 check_spends!(node_txn[0], revoked_local_txn[0]);
7939                 check_spends!(node_txn[1], revoked_local_txn[0]);
7940                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7941                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7942                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7943                 } else {
7944                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7945                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7946                 }
7947
7948                 node_txn.clear();
7949         };
7950
7951         // Few more blocks to confirm penalty txn
7952         connect_blocks(&nodes[0], 4);
7953         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7954         let header_144 = connect_blocks(&nodes[0], 9);
7955         let node_txn = {
7956                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7957                 assert_eq!(node_txn.len(), 1);
7958
7959                 assert_eq!(node_txn[0].input.len(), 2);
7960                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7961                 // Verify bumped tx is different and 25% bump heuristic
7962                 assert_ne!(first, node_txn[0].txid());
7963                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7964                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7965                 assert!(feerate_2 * 100 > feerate_1 * 125);
7966                 let txn = vec![node_txn[0].clone()];
7967                 node_txn.clear();
7968                 txn
7969         };
7970         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7971         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7972         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7973         connect_blocks(&nodes[0], 20);
7974         {
7975                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7976                 // We verify than no new transaction has been broadcast because previously
7977                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7978                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7979                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7980                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7981                 // up bumped justice generation.
7982                 assert_eq!(node_txn.len(), 0);
7983                 node_txn.clear();
7984         }
7985         check_closed_broadcast!(nodes[0], true);
7986         check_added_monitors!(nodes[0], 1);
7987 }
7988
7989 #[test]
7990 fn test_bump_penalty_txn_on_remote_commitment() {
7991         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7992         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7993
7994         // Create 2 HTLCs
7995         // Provide preimage for one
7996         // Check aggregation
7997
7998         let chanmon_cfgs = create_chanmon_cfgs(2);
7999         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8000         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8001         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8002
8003         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8004         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8005         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8006
8007         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8008         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8009         assert_eq!(remote_txn[0].output.len(), 4);
8010         assert_eq!(remote_txn[0].input.len(), 1);
8011         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8012
8013         // Claim a HTLC without revocation (provide B monitor with preimage)
8014         nodes[1].node.claim_funds(payment_preimage);
8015         mine_transaction(&nodes[1], &remote_txn[0]);
8016         check_added_monitors!(nodes[1], 2);
8017         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8018
8019         // One or more claim tx should have been broadcast, check it
8020         let timeout;
8021         let preimage;
8022         let preimage_bump;
8023         let feerate_timeout;
8024         let feerate_preimage;
8025         {
8026                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8027                 // 9 transactions including:
8028                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8029                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8030                 // 2 * HTLC-Success (one RBF bump we'll check later)
8031                 // 1 * HTLC-Timeout
8032                 assert_eq!(node_txn.len(), 8);
8033                 assert_eq!(node_txn[0].input.len(), 1);
8034                 assert_eq!(node_txn[6].input.len(), 1);
8035                 check_spends!(node_txn[0], remote_txn[0]);
8036                 check_spends!(node_txn[6], remote_txn[0]);
8037                 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
8038                 preimage_bump = node_txn[3].clone();
8039
8040                 check_spends!(node_txn[1], chan.3);
8041                 check_spends!(node_txn[2], node_txn[1]);
8042                 assert_eq!(node_txn[1], node_txn[4]);
8043                 assert_eq!(node_txn[2], node_txn[5]);
8044
8045                 timeout = node_txn[6].txid();
8046                 let index = node_txn[6].input[0].previous_output.vout;
8047                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8048                 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
8049
8050                 preimage = node_txn[0].txid();
8051                 let index = node_txn[0].input[0].previous_output.vout;
8052                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8053                 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
8054
8055                 node_txn.clear();
8056         };
8057         assert_ne!(feerate_timeout, 0);
8058         assert_ne!(feerate_preimage, 0);
8059
8060         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8061         connect_blocks(&nodes[1], 15);
8062         {
8063                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8064                 assert_eq!(node_txn.len(), 1);
8065                 assert_eq!(node_txn[0].input.len(), 1);
8066                 assert_eq!(preimage_bump.input.len(), 1);
8067                 check_spends!(node_txn[0], remote_txn[0]);
8068                 check_spends!(preimage_bump, remote_txn[0]);
8069
8070                 let index = preimage_bump.input[0].previous_output.vout;
8071                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8072                 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
8073                 assert!(new_feerate * 100 > feerate_timeout * 125);
8074                 assert_ne!(timeout, preimage_bump.txid());
8075
8076                 let index = node_txn[0].input[0].previous_output.vout;
8077                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8078                 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8079                 assert!(new_feerate * 100 > feerate_preimage * 125);
8080                 assert_ne!(preimage, node_txn[0].txid());
8081
8082                 node_txn.clear();
8083         }
8084
8085         nodes[1].node.get_and_clear_pending_events();
8086         nodes[1].node.get_and_clear_pending_msg_events();
8087 }
8088
8089 #[test]
8090 fn test_counterparty_raa_skip_no_crash() {
8091         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8092         // commitment transaction, we would have happily carried on and provided them the next
8093         // commitment transaction based on one RAA forward. This would probably eventually have led to
8094         // channel closure, but it would not have resulted in funds loss. Still, our
8095         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8096         // check simply that the channel is closed in response to such an RAA, but don't check whether
8097         // we decide to punish our counterparty for revoking their funds (as we don't currently
8098         // implement that).
8099         let chanmon_cfgs = create_chanmon_cfgs(2);
8100         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8101         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8102         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8103         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8104
8105         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8106         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8107
8108         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8109
8110         // Make signer believe we got a counterparty signature, so that it allows the revocation
8111         keys.get_enforcement_state().last_holder_commitment -= 1;
8112         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8113
8114         // Must revoke without gaps
8115         keys.get_enforcement_state().last_holder_commitment -= 1;
8116         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8117
8118         keys.get_enforcement_state().last_holder_commitment -= 1;
8119         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8120                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8121
8122         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8123                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8124         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8125         check_added_monitors!(nodes[1], 1);
8126         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8127 }
8128
8129 #[test]
8130 fn test_bump_txn_sanitize_tracking_maps() {
8131         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8132         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8133
8134         let chanmon_cfgs = create_chanmon_cfgs(2);
8135         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8136         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8137         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8138
8139         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8140         // Lock HTLC in both directions
8141         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8142         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8143
8144         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8145         assert_eq!(revoked_local_txn[0].input.len(), 1);
8146         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8147
8148         // Revoke local commitment tx
8149         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8150
8151         // Broadcast set of revoked txn on A
8152         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8153         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8154         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8155
8156         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8157         check_closed_broadcast!(nodes[0], true);
8158         check_added_monitors!(nodes[0], 1);
8159         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8160         let penalty_txn = {
8161                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8162                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8163                 check_spends!(node_txn[0], revoked_local_txn[0]);
8164                 check_spends!(node_txn[1], revoked_local_txn[0]);
8165                 check_spends!(node_txn[2], revoked_local_txn[0]);
8166                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8167                 node_txn.clear();
8168                 penalty_txn
8169         };
8170         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8171         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8172         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8173         {
8174                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8175                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8176                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8177                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8178                 }
8179         }
8180 }
8181
8182 #[test]
8183 fn test_override_channel_config() {
8184         let chanmon_cfgs = create_chanmon_cfgs(2);
8185         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8186         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8187         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8188
8189         // Node0 initiates a channel to node1 using the override config.
8190         let mut override_config = UserConfig::default();
8191         override_config.own_channel_config.our_to_self_delay = 200;
8192
8193         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8194
8195         // Assert the channel created by node0 is using the override config.
8196         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8197         assert_eq!(res.channel_flags, 0);
8198         assert_eq!(res.to_self_delay, 200);
8199 }
8200
8201 #[test]
8202 fn test_override_0msat_htlc_minimum() {
8203         let mut zero_config = UserConfig::default();
8204         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8205         let chanmon_cfgs = create_chanmon_cfgs(2);
8206         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8207         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8208         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8209
8210         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8211         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8212         assert_eq!(res.htlc_minimum_msat, 1);
8213
8214         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8215         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8216         assert_eq!(res.htlc_minimum_msat, 1);
8217 }
8218
8219 #[test]
8220 fn test_simple_mpp() {
8221         // Simple test of sending a multi-path payment.
8222         let chanmon_cfgs = create_chanmon_cfgs(4);
8223         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8224         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8225         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8226
8227         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8228         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8229         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8230         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8231         let logger = test_utils::TestLogger::new();
8232
8233         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[3]);
8234         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8235         let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[3].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8236         let path = route.paths[0].clone();
8237         route.paths.push(path);
8238         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8239         route.paths[0][0].short_channel_id = chan_1_id;
8240         route.paths[0][1].short_channel_id = chan_3_id;
8241         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8242         route.paths[1][0].short_channel_id = chan_2_id;
8243         route.paths[1][1].short_channel_id = chan_4_id;
8244         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8245         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8246 }
8247
8248 #[test]
8249 fn test_preimage_storage() {
8250         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8251         let chanmon_cfgs = create_chanmon_cfgs(2);
8252         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8253         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8254         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8255
8256         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8257
8258         {
8259                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, 42);
8260
8261                 let logger = test_utils::TestLogger::new();
8262                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8263                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100_000, TEST_FINAL_CLTV, &logger).unwrap();
8264                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8265                 check_added_monitors!(nodes[0], 1);
8266                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8267                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8268                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8269                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8270         }
8271         // Note that after leaving the above scope we have no knowledge of any arguments or return
8272         // values from previous calls.
8273         expect_pending_htlcs_forwardable!(nodes[1]);
8274         let events = nodes[1].node.get_and_clear_pending_events();
8275         assert_eq!(events.len(), 1);
8276         match events[0] {
8277                 Event::PaymentReceived { ref purpose, .. } => {
8278                         match &purpose {
8279                                 PaymentPurpose::InvoicePayment { payment_preimage, user_payment_id, .. } => {
8280                                         assert_eq!(*user_payment_id, 42);
8281                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8282                                 },
8283                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8284                         }
8285                 },
8286                 _ => panic!("Unexpected event"),
8287         }
8288 }
8289
8290 #[test]
8291 fn test_secret_timeout() {
8292         // Simple test of payment secret storage time outs
8293         let chanmon_cfgs = create_chanmon_cfgs(2);
8294         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8295         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8296         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8297
8298         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8299
8300         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8301
8302         // We should fail to register the same payment hash twice, at least until we've connected a
8303         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8304         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8305                 assert_eq!(err, "Duplicate payment hash");
8306         } else { panic!(); }
8307         let mut block = {
8308                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8309                 Block {
8310                         header: BlockHeader {
8311                                 version: 0x2000000,
8312                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8313                                 merkle_root: Default::default(),
8314                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8315                         txdata: vec![],
8316                 }
8317         };
8318         connect_block(&nodes[1], &block);
8319         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8320                 assert_eq!(err, "Duplicate payment hash");
8321         } else { panic!(); }
8322
8323         // If we then connect the second block, we should be able to register the same payment hash
8324         // again with a different user_payment_id (this time getting a new payment secret).
8325         block.header.prev_blockhash = block.header.block_hash();
8326         block.header.time += 1;
8327         connect_block(&nodes[1], &block);
8328         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 42).unwrap();
8329         assert_ne!(payment_secret_1, our_payment_secret);
8330
8331         {
8332                 let logger = test_utils::TestLogger::new();
8333                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8334                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100_000, TEST_FINAL_CLTV, &logger).unwrap();
8335                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8336                 check_added_monitors!(nodes[0], 1);
8337                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8338                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8339                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8340                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8341         }
8342         // Note that after leaving the above scope we have no knowledge of any arguments or return
8343         // values from previous calls.
8344         expect_pending_htlcs_forwardable!(nodes[1]);
8345         let events = nodes[1].node.get_and_clear_pending_events();
8346         assert_eq!(events.len(), 1);
8347         match events[0] {
8348                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, user_payment_id }, .. } => {
8349                         assert!(payment_preimage.is_none());
8350                         assert_eq!(user_payment_id, 42);
8351                         assert_eq!(payment_secret, our_payment_secret);
8352                         // We don't actually have the payment preimage with which to claim this payment!
8353                 },
8354                 _ => panic!("Unexpected event"),
8355         }
8356 }
8357
8358 #[test]
8359 fn test_bad_secret_hash() {
8360         // Simple test of unregistered payment hash/invalid payment secret handling
8361         let chanmon_cfgs = create_chanmon_cfgs(2);
8362         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8363         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8364         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8365
8366         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8367
8368         let random_payment_hash = PaymentHash([42; 32]);
8369         let random_payment_secret = PaymentSecret([43; 32]);
8370         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8371
8372         let logger = test_utils::TestLogger::new();
8373         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8374         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100_000, TEST_FINAL_CLTV, &logger).unwrap();
8375
8376         // All the below cases should end up being handled exactly identically, so we macro the
8377         // resulting events.
8378         macro_rules! handle_unknown_invalid_payment_data {
8379                 () => {
8380                         check_added_monitors!(nodes[0], 1);
8381                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8382                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8383                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8384                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8385
8386                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8387                         // again to process the pending backwards-failure of the HTLC
8388                         expect_pending_htlcs_forwardable!(nodes[1]);
8389                         expect_pending_htlcs_forwardable!(nodes[1]);
8390                         check_added_monitors!(nodes[1], 1);
8391
8392                         // We should fail the payment back
8393                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8394                         match events.pop().unwrap() {
8395                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8396                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8397                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8398                                 },
8399                                 _ => panic!("Unexpected event"),
8400                         }
8401                 }
8402         }
8403
8404         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8405         // Error data is the HTLC value (100,000) and current block height
8406         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8407
8408         // Send a payment with the right payment hash but the wrong payment secret
8409         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8410         handle_unknown_invalid_payment_data!();
8411         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8412
8413         // Send a payment with a random payment hash, but the right payment secret
8414         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8415         handle_unknown_invalid_payment_data!();
8416         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8417
8418         // Send a payment with a random payment hash and random payment secret
8419         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8420         handle_unknown_invalid_payment_data!();
8421         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8422 }
8423
8424 #[test]
8425 fn test_update_err_monitor_lockdown() {
8426         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8427         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8428         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8429         //
8430         // This scenario may happen in a watchtower setup, where watchtower process a block height
8431         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8432         // commitment at same time.
8433
8434         let chanmon_cfgs = create_chanmon_cfgs(2);
8435         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8436         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8437         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8438
8439         // Create some initial channel
8440         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8441         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8442
8443         // Rebalance the network to generate htlc in the two directions
8444         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8445
8446         // Route a HTLC from node 0 to node 1 (but don't settle)
8447         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8448
8449         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8450         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8451         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8452         let persister = test_utils::TestPersister::new();
8453         let watchtower = {
8454                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8455                 let monitor = monitors.get(&outpoint).unwrap();
8456                 let mut w = test_utils::TestVecWriter(Vec::new());
8457                 monitor.write(&mut w).unwrap();
8458                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8459                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8460                 assert!(new_monitor == *monitor);
8461                 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);
8462                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8463                 watchtower
8464         };
8465         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8466         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8467         // transaction lock time requirements here.
8468         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8469         watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8470
8471         // Try to update ChannelMonitor
8472         assert!(nodes[1].node.claim_funds(preimage));
8473         check_added_monitors!(nodes[1], 1);
8474         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8475         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8476         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8477         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8478                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8479                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8480                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8481                 } else { assert!(false); }
8482         } else { assert!(false); };
8483         // Our local monitor is in-sync and hasn't processed yet timeout
8484         check_added_monitors!(nodes[0], 1);
8485         let events = nodes[0].node.get_and_clear_pending_events();
8486         assert_eq!(events.len(), 1);
8487 }
8488
8489 #[test]
8490 fn test_concurrent_monitor_claim() {
8491         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8492         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8493         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8494         // state N+1 confirms. Alice claims output from state N+1.
8495
8496         let chanmon_cfgs = create_chanmon_cfgs(2);
8497         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8498         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8499         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8500
8501         // Create some initial channel
8502         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8503         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8504
8505         // Rebalance the network to generate htlc in the two directions
8506         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8507
8508         // Route a HTLC from node 0 to node 1 (but don't settle)
8509         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8510
8511         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8512         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8513         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8514         let persister = test_utils::TestPersister::new();
8515         let watchtower_alice = {
8516                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8517                 let monitor = monitors.get(&outpoint).unwrap();
8518                 let mut w = test_utils::TestVecWriter(Vec::new());
8519                 monitor.write(&mut w).unwrap();
8520                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8521                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8522                 assert!(new_monitor == *monitor);
8523                 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);
8524                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8525                 watchtower
8526         };
8527         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8528         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8529         // transaction lock time requirements here.
8530         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8531         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8532
8533         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8534         {
8535                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8536                 assert_eq!(txn.len(), 2);
8537                 txn.clear();
8538         }
8539
8540         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8541         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8542         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8543         let persister = test_utils::TestPersister::new();
8544         let watchtower_bob = {
8545                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8546                 let monitor = monitors.get(&outpoint).unwrap();
8547                 let mut w = test_utils::TestVecWriter(Vec::new());
8548                 monitor.write(&mut w).unwrap();
8549                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8550                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8551                 assert!(new_monitor == *monitor);
8552                 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);
8553                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8554                 watchtower
8555         };
8556         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8557         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8558
8559         // Route another payment to generate another update with still previous HTLC pending
8560         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
8561         {
8562                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8563                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3000000 , TEST_FINAL_CLTV, &logger).unwrap();
8564                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8565         }
8566         check_added_monitors!(nodes[1], 1);
8567
8568         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8569         assert_eq!(updates.update_add_htlcs.len(), 1);
8570         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8571         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8572                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8573                         // Watchtower Alice should already have seen the block and reject the update
8574                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8575                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8576                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8577                 } else { assert!(false); }
8578         } else { assert!(false); };
8579         // Our local monitor is in-sync and hasn't processed yet timeout
8580         check_added_monitors!(nodes[0], 1);
8581
8582         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8583         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8584         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8585
8586         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8587         let bob_state_y;
8588         {
8589                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8590                 assert_eq!(txn.len(), 2);
8591                 bob_state_y = txn[0].clone();
8592                 txn.clear();
8593         };
8594
8595         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8596         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8597         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);
8598         {
8599                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8600                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8601                 // the onchain detection of the HTLC output
8602                 assert_eq!(htlc_txn.len(), 2);
8603                 check_spends!(htlc_txn[0], bob_state_y);
8604                 check_spends!(htlc_txn[1], bob_state_y);
8605         }
8606 }
8607
8608 #[test]
8609 fn test_pre_lockin_no_chan_closed_update() {
8610         // Test that if a peer closes a channel in response to a funding_created message we don't
8611         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8612         // message).
8613         //
8614         // Doing so would imply a channel monitor update before the initial channel monitor
8615         // registration, violating our API guarantees.
8616         //
8617         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8618         // then opening a second channel with the same funding output as the first (which is not
8619         // rejected because the first channel does not exist in the ChannelManager) and closing it
8620         // before receiving funding_signed.
8621         let chanmon_cfgs = create_chanmon_cfgs(2);
8622         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8623         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8624         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8625
8626         // Create an initial channel
8627         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8628         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8629         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8630         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8631         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8632
8633         // Move the first channel through the funding flow...
8634         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8635
8636         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8637         check_added_monitors!(nodes[0], 0);
8638
8639         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8640         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8641         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8642         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8643         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8644 }
8645
8646 #[test]
8647 fn test_htlc_no_detection() {
8648         // This test is a mutation to underscore the detection logic bug we had
8649         // before #653. HTLC value routed is above the remaining balance, thus
8650         // inverting HTLC and `to_remote` output. HTLC will come second and
8651         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8652         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8653         // outputs order detection for correct spending children filtring.
8654
8655         let chanmon_cfgs = create_chanmon_cfgs(2);
8656         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8657         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8658         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8659
8660         // Create some initial channels
8661         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8662
8663         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8664         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8665         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8666         assert_eq!(local_txn[0].input.len(), 1);
8667         assert_eq!(local_txn[0].output.len(), 3);
8668         check_spends!(local_txn[0], chan_1.3);
8669
8670         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8671         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8672         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8673         // We deliberately connect the local tx twice as this should provoke a failure calling
8674         // this test before #653 fix.
8675         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);
8676         check_closed_broadcast!(nodes[0], true);
8677         check_added_monitors!(nodes[0], 1);
8678         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8679         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8680
8681         let htlc_timeout = {
8682                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8683                 assert_eq!(node_txn[1].input.len(), 1);
8684                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8685                 check_spends!(node_txn[1], local_txn[0]);
8686                 node_txn[1].clone()
8687         };
8688
8689         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8690         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8691         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8692         expect_payment_failed!(nodes[0], our_payment_hash, true);
8693 }
8694
8695 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8696         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8697         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8698         // Carol, Alice would be the upstream node, and Carol the downstream.)
8699         //
8700         // Steps of the test:
8701         // 1) Alice sends a HTLC to Carol through Bob.
8702         // 2) Carol doesn't settle the HTLC.
8703         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8704         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8705         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8706         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8707         // 5) Carol release the preimage to Bob off-chain.
8708         // 6) Bob claims the offered output on the broadcasted commitment.
8709         let chanmon_cfgs = create_chanmon_cfgs(3);
8710         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8711         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8712         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8713
8714         // Create some initial channels
8715         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8716         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8717
8718         // Steps (1) and (2):
8719         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8720         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8721
8722         // Check that Alice's commitment transaction now contains an output for this HTLC.
8723         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8724         check_spends!(alice_txn[0], chan_ab.3);
8725         assert_eq!(alice_txn[0].output.len(), 2);
8726         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8727         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8728         assert_eq!(alice_txn.len(), 2);
8729
8730         // Steps (3) and (4):
8731         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8732         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8733         let mut force_closing_node = 0; // Alice force-closes
8734         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8735         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8736         check_closed_broadcast!(nodes[force_closing_node], true);
8737         check_added_monitors!(nodes[force_closing_node], 1);
8738         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8739         if go_onchain_before_fulfill {
8740                 let txn_to_broadcast = match broadcast_alice {
8741                         true => alice_txn.clone(),
8742                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8743                 };
8744                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8745                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8746                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8747                 if broadcast_alice {
8748                         check_closed_broadcast!(nodes[1], true);
8749                         check_added_monitors!(nodes[1], 1);
8750                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8751                 }
8752                 assert_eq!(bob_txn.len(), 1);
8753                 check_spends!(bob_txn[0], chan_ab.3);
8754         }
8755
8756         // Step (5):
8757         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8758         // process of removing the HTLC from their commitment transactions.
8759         assert!(nodes[2].node.claim_funds(payment_preimage));
8760         check_added_monitors!(nodes[2], 1);
8761         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8762         assert!(carol_updates.update_add_htlcs.is_empty());
8763         assert!(carol_updates.update_fail_htlcs.is_empty());
8764         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8765         assert!(carol_updates.update_fee.is_none());
8766         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8767
8768         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8769         expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8770         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8771         if !go_onchain_before_fulfill && broadcast_alice {
8772                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8773                 assert_eq!(events.len(), 1);
8774                 match events[0] {
8775                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8776                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8777                         },
8778                         _ => panic!("Unexpected event"),
8779                 };
8780         }
8781         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8782         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8783         // Carol<->Bob's updated commitment transaction info.
8784         check_added_monitors!(nodes[1], 2);
8785
8786         let events = nodes[1].node.get_and_clear_pending_msg_events();
8787         assert_eq!(events.len(), 2);
8788         let bob_revocation = match events[0] {
8789                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8790                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8791                         (*msg).clone()
8792                 },
8793                 _ => panic!("Unexpected event"),
8794         };
8795         let bob_updates = match events[1] {
8796                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8797                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8798                         (*updates).clone()
8799                 },
8800                 _ => panic!("Unexpected event"),
8801         };
8802
8803         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8804         check_added_monitors!(nodes[2], 1);
8805         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8806         check_added_monitors!(nodes[2], 1);
8807
8808         let events = nodes[2].node.get_and_clear_pending_msg_events();
8809         assert_eq!(events.len(), 1);
8810         let carol_revocation = match events[0] {
8811                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8812                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8813                         (*msg).clone()
8814                 },
8815                 _ => panic!("Unexpected event"),
8816         };
8817         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8818         check_added_monitors!(nodes[1], 1);
8819
8820         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8821         // here's where we put said channel's commitment tx on-chain.
8822         let mut txn_to_broadcast = alice_txn.clone();
8823         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8824         if !go_onchain_before_fulfill {
8825                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8826                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8827                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8828                 if broadcast_alice {
8829                         check_closed_broadcast!(nodes[1], true);
8830                         check_added_monitors!(nodes[1], 1);
8831                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8832                 }
8833                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8834                 if broadcast_alice {
8835                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8836                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8837                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8838                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8839                         // broadcasted.
8840                         assert_eq!(bob_txn.len(), 3);
8841                         check_spends!(bob_txn[1], chan_ab.3);
8842                 } else {
8843                         assert_eq!(bob_txn.len(), 2);
8844                         check_spends!(bob_txn[0], chan_ab.3);
8845                 }
8846         }
8847
8848         // Step (6):
8849         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8850         // broadcasted commitment transaction.
8851         {
8852                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8853                 if go_onchain_before_fulfill {
8854                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8855                         assert_eq!(bob_txn.len(), 2);
8856                 }
8857                 let script_weight = match broadcast_alice {
8858                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8859                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8860                 };
8861                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8862                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8863                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8864                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8865                 if broadcast_alice && !go_onchain_before_fulfill {
8866                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8867                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8868                 } else {
8869                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8870                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8871                 }
8872         }
8873 }
8874
8875 #[test]
8876 fn test_onchain_htlc_settlement_after_close() {
8877         do_test_onchain_htlc_settlement_after_close(true, true);
8878         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8879         do_test_onchain_htlc_settlement_after_close(true, false);
8880         do_test_onchain_htlc_settlement_after_close(false, false);
8881 }
8882
8883 #[test]
8884 fn test_duplicate_chan_id() {
8885         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8886         // already open we reject it and keep the old channel.
8887         //
8888         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8889         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8890         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8891         // updating logic for the existing channel.
8892         let chanmon_cfgs = create_chanmon_cfgs(2);
8893         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8894         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8895         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8896
8897         // Create an initial channel
8898         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8899         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8900         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8901         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()));
8902
8903         // Try to create a second channel with the same temporary_channel_id as the first and check
8904         // that it is rejected.
8905         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8906         {
8907                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8908                 assert_eq!(events.len(), 1);
8909                 match events[0] {
8910                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8911                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8912                                 // first (valid) and second (invalid) channels are closed, given they both have
8913                                 // the same non-temporary channel_id. However, currently we do not, so we just
8914                                 // move forward with it.
8915                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8916                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8917                         },
8918                         _ => panic!("Unexpected event"),
8919                 }
8920         }
8921
8922         // Move the first channel through the funding flow...
8923         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8924
8925         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8926         check_added_monitors!(nodes[0], 0);
8927
8928         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8929         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8930         {
8931                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8932                 assert_eq!(added_monitors.len(), 1);
8933                 assert_eq!(added_monitors[0].0, funding_output);
8934                 added_monitors.clear();
8935         }
8936         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8937
8938         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8939         let channel_id = funding_outpoint.to_channel_id();
8940
8941         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8942         // temporary one).
8943
8944         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8945         // Technically this is allowed by the spec, but we don't support it and there's little reason
8946         // to. Still, it shouldn't cause any other issues.
8947         open_chan_msg.temporary_channel_id = channel_id;
8948         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8949         {
8950                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8951                 assert_eq!(events.len(), 1);
8952                 match events[0] {
8953                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8954                                 // Technically, at this point, nodes[1] would be justified in thinking both
8955                                 // channels are closed, but currently we do not, so we just move forward with it.
8956                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8957                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8958                         },
8959                         _ => panic!("Unexpected event"),
8960                 }
8961         }
8962
8963         // Now try to create a second channel which has a duplicate funding output.
8964         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8965         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8966         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8967         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()));
8968         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8969
8970         let funding_created = {
8971                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8972                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8973                 let logger = test_utils::TestLogger::new();
8974                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8975         };
8976         check_added_monitors!(nodes[0], 0);
8977         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8978         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8979         // still needs to be cleared here.
8980         check_added_monitors!(nodes[1], 1);
8981
8982         // ...still, nodes[1] will reject the duplicate channel.
8983         {
8984                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8985                 assert_eq!(events.len(), 1);
8986                 match events[0] {
8987                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8988                                 // Technically, at this point, nodes[1] would be justified in thinking both
8989                                 // channels are closed, but currently we do not, so we just move forward with it.
8990                                 assert_eq!(msg.channel_id, channel_id);
8991                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8992                         },
8993                         _ => panic!("Unexpected event"),
8994                 }
8995         }
8996
8997         // finally, finish creating the original channel and send a payment over it to make sure
8998         // everything is functional.
8999         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9000         {
9001                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9002                 assert_eq!(added_monitors.len(), 1);
9003                 assert_eq!(added_monitors[0].0, funding_output);
9004                 added_monitors.clear();
9005         }
9006
9007         let events_4 = nodes[0].node.get_and_clear_pending_events();
9008         assert_eq!(events_4.len(), 0);
9009         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9010         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9011
9012         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9013         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9014         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9015         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9016 }
9017
9018 #[test]
9019 fn test_error_chans_closed() {
9020         // Test that we properly handle error messages, closing appropriate channels.
9021         //
9022         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9023         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9024         // we can test various edge cases around it to ensure we don't regress.
9025         let chanmon_cfgs = create_chanmon_cfgs(3);
9026         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9027         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9028         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9029
9030         // Create some initial channels
9031         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9032         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9033         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9034
9035         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9036         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9037         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9038
9039         // Closing a channel from a different peer has no effect
9040         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9041         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9042
9043         // Closing one channel doesn't impact others
9044         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9045         check_added_monitors!(nodes[0], 1);
9046         check_closed_broadcast!(nodes[0], false);
9047         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9048         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9049         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9050         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);
9051         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);
9052
9053         // A null channel ID should close all channels
9054         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9055         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9056         check_added_monitors!(nodes[0], 2);
9057         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9058         let events = nodes[0].node.get_and_clear_pending_msg_events();
9059         assert_eq!(events.len(), 2);
9060         match events[0] {
9061                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9062                         assert_eq!(msg.contents.flags & 2, 2);
9063                 },
9064                 _ => panic!("Unexpected event"),
9065         }
9066         match events[1] {
9067                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9068                         assert_eq!(msg.contents.flags & 2, 2);
9069                 },
9070                 _ => panic!("Unexpected event"),
9071         }
9072         // Note that at this point users of a standard PeerHandler will end up calling
9073         // peer_disconnected with no_connection_possible set to false, duplicating the
9074         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9075         // users with their own peer handling logic. We duplicate the call here, however.
9076         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9077         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9078
9079         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9080         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9081         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9082 }
9083
9084 #[test]
9085 fn test_invalid_funding_tx() {
9086         // Test that we properly handle invalid funding transactions sent to us from a peer.
9087         //
9088         // Previously, all other major lightning implementations had failed to properly sanitize
9089         // funding transactions from their counterparties, leading to a multi-implementation critical
9090         // security vulnerability (though we always sanitized properly, we've previously had
9091         // un-released crashes in the sanitization process).
9092         let chanmon_cfgs = create_chanmon_cfgs(2);
9093         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9094         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9095         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9096
9097         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9098         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()));
9099         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()));
9100
9101         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
9102         for output in tx.output.iter_mut() {
9103                 // Make the confirmed funding transaction have a bogus script_pubkey
9104                 output.script_pubkey = bitcoin::Script::new();
9105         }
9106
9107         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
9108         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()));
9109         check_added_monitors!(nodes[1], 1);
9110
9111         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()));
9112         check_added_monitors!(nodes[0], 1);
9113
9114         let events_1 = nodes[0].node.get_and_clear_pending_events();
9115         assert_eq!(events_1.len(), 0);
9116
9117         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9118         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9119         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9120
9121         confirm_transaction_at(&nodes[1], &tx, 1);
9122         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9123         check_added_monitors!(nodes[1], 1);
9124         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9125         assert_eq!(events_2.len(), 1);
9126         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9127                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9128                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9129                         assert_eq!(msg.data, "funding tx had wrong script/value or output index");
9130                 } else { panic!(); }
9131         } else { panic!(); }
9132         assert_eq!(nodes[1].node.list_channels().len(), 0);
9133 }
9134
9135 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9136         // In the first version of the chain::Confirm interface, after a refactor was made to not
9137         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9138         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9139         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9140         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9141         // spending transaction until height N+1 (or greater). This was due to the way
9142         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9143         // spending transaction at the height the input transaction was confirmed at, not whether we
9144         // should broadcast a spending transaction at the current height.
9145         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9146         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9147         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9148         // until we learned about an additional block.
9149         //
9150         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9151         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9152         let chanmon_cfgs = create_chanmon_cfgs(3);
9153         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9154         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9155         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9156         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9157
9158         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9159         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9160         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9161         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9162         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9163
9164         nodes[1].node.force_close_channel(&channel_id).unwrap();
9165         check_closed_broadcast!(nodes[1], true);
9166         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9167         check_added_monitors!(nodes[1], 1);
9168         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9169         assert_eq!(node_txn.len(), 1);
9170
9171         let conf_height = nodes[1].best_block_info().1;
9172         if !test_height_before_timelock {
9173                 connect_blocks(&nodes[1], 24 * 6);
9174         }
9175         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9176                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9177         if test_height_before_timelock {
9178                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9179                 // generate any events or broadcast any transactions
9180                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9181                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9182         } else {
9183                 // We should broadcast an HTLC transaction spending our funding transaction first
9184                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9185                 assert_eq!(spending_txn.len(), 2);
9186                 assert_eq!(spending_txn[0], node_txn[0]);
9187                 check_spends!(spending_txn[1], node_txn[0]);
9188                 // We should also generate a SpendableOutputs event with the to_self output (as its
9189                 // timelock is up).
9190                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9191                 assert_eq!(descriptor_spend_txn.len(), 1);
9192
9193                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9194                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9195                 // additional block built on top of the current chain.
9196                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9197                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9198                 expect_pending_htlcs_forwardable!(nodes[1]);
9199                 check_added_monitors!(nodes[1], 1);
9200
9201                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9202                 assert!(updates.update_add_htlcs.is_empty());
9203                 assert!(updates.update_fulfill_htlcs.is_empty());
9204                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9205                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9206                 assert!(updates.update_fee.is_none());
9207                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9208                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9209                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9210         }
9211 }
9212
9213 #[test]
9214 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9215         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9216         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9217 }
9218
9219 #[test]
9220 fn test_forwardable_regen() {
9221         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9222         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9223         // HTLCs.
9224         // We test it for both payment receipt and payment forwarding.
9225
9226         let chanmon_cfgs = create_chanmon_cfgs(3);
9227         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9228         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9229         let persister: test_utils::TestPersister;
9230         let new_chain_monitor: test_utils::TestChainMonitor;
9231         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9232         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9233         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9234         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9235
9236         // First send a payment to nodes[1]
9237         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9238         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9239         check_added_monitors!(nodes[0], 1);
9240
9241         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9242         assert_eq!(events.len(), 1);
9243         let payment_event = SendEvent::from_event(events.pop().unwrap());
9244         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9245         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9246
9247         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9248
9249         // Next send a payment which is forwarded by nodes[1]
9250         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9251         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9252         check_added_monitors!(nodes[0], 1);
9253
9254         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9255         assert_eq!(events.len(), 1);
9256         let payment_event = SendEvent::from_event(events.pop().unwrap());
9257         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9258         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9259
9260         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9261         // generated
9262         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9263
9264         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9265         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9266         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9267
9268         let nodes_1_serialized = nodes[1].node.encode();
9269         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9270         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9271         {
9272                 let monitors = nodes[1].chain_monitor.chain_monitor.monitors.read().unwrap();
9273                 let mut monitor_iter = monitors.iter();
9274                 monitor_iter.next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
9275                 monitor_iter.next().unwrap().1.write(&mut chan_1_monitor_serialized).unwrap();
9276         }
9277
9278         persister = test_utils::TestPersister::new();
9279         let keys_manager = &chanmon_cfgs[1].keys_manager;
9280         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);
9281         nodes[1].chain_monitor = &new_chain_monitor;
9282
9283         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9284         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9285                 &mut chan_0_monitor_read, keys_manager).unwrap();
9286         assert!(chan_0_monitor_read.is_empty());
9287         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9288         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9289                 &mut chan_1_monitor_read, keys_manager).unwrap();
9290         assert!(chan_1_monitor_read.is_empty());
9291
9292         let mut nodes_1_read = &nodes_1_serialized[..];
9293         let (_, nodes_1_deserialized_tmp) = {
9294                 let mut channel_monitors = HashMap::new();
9295                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9296                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9297                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9298                         default_config: UserConfig::default(),
9299                         keys_manager,
9300                         fee_estimator: node_cfgs[1].fee_estimator,
9301                         chain_monitor: nodes[1].chain_monitor,
9302                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9303                         logger: nodes[1].logger,
9304                         channel_monitors,
9305                 }).unwrap()
9306         };
9307         nodes_1_deserialized = nodes_1_deserialized_tmp;
9308         assert!(nodes_1_read.is_empty());
9309
9310         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9311         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9312         nodes[1].node = &nodes_1_deserialized;
9313         check_added_monitors!(nodes[1], 2);
9314
9315         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9316         // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9317         // the commitment state.
9318         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9319
9320         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9321
9322         expect_pending_htlcs_forwardable!(nodes[1]);
9323         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9324         check_added_monitors!(nodes[1], 1);
9325
9326         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9327         assert_eq!(events.len(), 1);
9328         let payment_event = SendEvent::from_event(events.pop().unwrap());
9329         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9330         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9331         expect_pending_htlcs_forwardable!(nodes[2]);
9332         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9333
9334         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9335         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9336 }
9337
9338 #[test]
9339 fn test_keysend_payments_to_public_node() {
9340         let chanmon_cfgs = create_chanmon_cfgs(2);
9341         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9342         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9343         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9344
9345         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9346         let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9347         let payer_pubkey = nodes[0].node.get_our_node_id();
9348         let payee_pubkey = nodes[1].node.get_our_node_id();
9349         let route = get_route(&payer_pubkey, network_graph, &payee_pubkey, None,
9350                         None, &vec![], 10000, 40,
9351                         nodes[0].logger).unwrap();
9352
9353         let test_preimage = PaymentPreimage([42; 32]);
9354         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9355         check_added_monitors!(nodes[0], 1);
9356         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9357         assert_eq!(events.len(), 1);
9358         let event = events.pop().unwrap();
9359         let path = vec![&nodes[1]];
9360         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9361         claim_payment(&nodes[0], &path, test_preimage);
9362 }
9363
9364 #[test]
9365 fn test_keysend_payments_to_private_node() {
9366         let chanmon_cfgs = create_chanmon_cfgs(2);
9367         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9368         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9369         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9370
9371         let payer_pubkey = nodes[0].node.get_our_node_id();
9372         let payee_pubkey = nodes[1].node.get_our_node_id();
9373         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9374         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9375
9376         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9377         let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9378         let first_hops = nodes[0].node.list_usable_channels();
9379         let route = get_keysend_route(&payer_pubkey, &network_graph, &payee_pubkey,
9380                                 Some(&first_hops.iter().collect::<Vec<_>>()), &vec![], 10000, 40,
9381                                 nodes[0].logger).unwrap();
9382
9383         let test_preimage = PaymentPreimage([42; 32]);
9384         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9385         check_added_monitors!(nodes[0], 1);
9386         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9387         assert_eq!(events.len(), 1);
9388         let event = events.pop().unwrap();
9389         let path = vec![&nodes[1]];
9390         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9391         claim_payment(&nodes[0], &path, test_preimage);
9392 }