Correct error when a peer opens a channel with a huge push_msat
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use chain;
15 use chain::{Confirm, Listen, Watch};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{BaseSign, KeysInterface};
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS };
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
26 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
27 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
28 use ln::msgs;
29 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
30 use util::enforcing_trait_impls::EnforcingSigner;
31 use util::{byte_utils, test_utils};
32 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
33 use util::errors::APIError;
34 use util::ser::{Writeable, ReadableArgs};
35 use util::config::UserConfig;
36
37 use bitcoin::hash_types::BlockHash;
38 use bitcoin::blockdata::block::{Block, BlockHeader};
39 use bitcoin::blockdata::script::Builder;
40 use bitcoin::blockdata::opcodes;
41 use bitcoin::blockdata::constants::genesis_block;
42 use bitcoin::network::constants::Network;
43
44 use bitcoin::secp256k1::Secp256k1;
45 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
46
47 use regex;
48
49 use io;
50 use prelude::*;
51 use alloc::collections::BTreeSet;
52 use core::default::Default;
53 use sync::{Arc, Mutex};
54
55 use ln::functional_test_utils::*;
56 use ln::chan_utils::CommitmentTransaction;
57
58 #[test]
59 fn test_insane_channel_opens() {
60         // Stand up a network of 2 nodes
61         let chanmon_cfgs = create_chanmon_cfgs(2);
62         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
63         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
64         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
65
66         // Instantiate channel parameters where we push the maximum msats given our
67         // funding satoshis
68         let channel_value_sat = 31337; // same as funding satoshis
69         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
70         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
71
72         // Have node0 initiate a channel to node1 with aforementioned parameters
73         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
74
75         // Extract the channel open message from node0 to node1
76         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
77
78         // Test helper that asserts we get the correct error string given a mutator
79         // that supposedly makes the channel open message insane
80         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
81                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
82                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
83                 assert_eq!(msg_events.len(), 1);
84                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
85                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
86                         match action {
87                                 &ErrorAction::SendErrorMessage { .. } => {
88                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
89                                 },
90                                 _ => panic!("unexpected event!"),
91                         }
92                 } else { assert!(false); }
93         };
94
95         use ln::channel::MAX_FUNDING_SATOSHIS;
96         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
97
98         // Test all mutations that would make the channel open message insane
99         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 });
100
101         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
102
103         insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
104
105         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
106
107         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 });
108
109         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 });
110
111         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
112
113         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
114 }
115
116 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
117         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
118         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
119         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
120         // in normal testing, we test it explicitly here.
121         let chanmon_cfgs = create_chanmon_cfgs(2);
122         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
123         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
124         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
125
126         // Have node0 initiate a channel to node1 with aforementioned parameters
127         let mut push_amt = 100_000_000;
128         let feerate_per_kw = 253;
129         let opt_anchors = false;
130         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
131         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
132
133         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
134         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
135         if !send_from_initiator {
136                 open_channel_message.channel_reserve_satoshis = 0;
137                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
138         }
139         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
140
141         // Extract the channel accept message from node1 to node0
142         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
143         if send_from_initiator {
144                 accept_channel_message.channel_reserve_satoshis = 0;
145                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
146         }
147         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
148         {
149                 let mut lock;
150                 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
151                 chan.holder_selected_channel_reserve_satoshis = 0;
152                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
153         }
154
155         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
156         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
157         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
158
159         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
160         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
161         if send_from_initiator {
162                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
163                         // Note that for outbound channels we have to consider the commitment tx fee and the
164                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
165                         // well as an additional HTLC.
166                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
167         } else {
168                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
169         }
170 }
171
172 #[test]
173 fn test_counterparty_no_reserve() {
174         do_test_counterparty_no_reserve(true);
175         do_test_counterparty_no_reserve(false);
176 }
177
178 #[test]
179 fn test_async_inbound_update_fee() {
180         let chanmon_cfgs = create_chanmon_cfgs(2);
181         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
182         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
183         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
184         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
185
186         // balancing
187         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
188
189         // A                                        B
190         // update_fee                            ->
191         // send (1) commitment_signed            -.
192         //                                       <- update_add_htlc/commitment_signed
193         // send (2) RAA (awaiting remote revoke) -.
194         // (1) commitment_signed is delivered    ->
195         //                                       .- send (3) RAA (awaiting remote revoke)
196         // (2) RAA is delivered                  ->
197         //                                       .- send (4) commitment_signed
198         //                                       <- (3) RAA is delivered
199         // send (5) commitment_signed            -.
200         //                                       <- (4) commitment_signed is delivered
201         // send (6) RAA                          -.
202         // (5) commitment_signed is delivered    ->
203         //                                       <- RAA
204         // (6) RAA is delivered                  ->
205
206         // First nodes[0] generates an update_fee
207         {
208                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
209                 *feerate_lock += 20;
210         }
211         nodes[0].node.timer_tick_occurred();
212         check_added_monitors!(nodes[0], 1);
213
214         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
215         assert_eq!(events_0.len(), 1);
216         let (update_msg, commitment_signed) = match events_0[0] { // (1)
217                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
218                         (update_fee.as_ref(), commitment_signed)
219                 },
220                 _ => panic!("Unexpected event"),
221         };
222
223         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
224
225         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
226         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
227         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
228         check_added_monitors!(nodes[1], 1);
229
230         let payment_event = {
231                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
232                 assert_eq!(events_1.len(), 1);
233                 SendEvent::from_event(events_1.remove(0))
234         };
235         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
236         assert_eq!(payment_event.msgs.len(), 1);
237
238         // ...now when the messages get delivered everyone should be happy
239         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
240         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
241         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
242         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
243         check_added_monitors!(nodes[0], 1);
244
245         // deliver(1), generate (3):
246         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
247         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
248         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
249         check_added_monitors!(nodes[1], 1);
250
251         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
252         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
253         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
254         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
255         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
256         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
257         assert!(bs_update.update_fee.is_none()); // (4)
258         check_added_monitors!(nodes[1], 1);
259
260         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
261         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
262         assert!(as_update.update_add_htlcs.is_empty()); // (5)
263         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
264         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
265         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
266         assert!(as_update.update_fee.is_none()); // (5)
267         check_added_monitors!(nodes[0], 1);
268
269         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
270         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
271         // only (6) so get_event_msg's assert(len == 1) passes
272         check_added_monitors!(nodes[0], 1);
273
274         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
275         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
276         check_added_monitors!(nodes[1], 1);
277
278         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
279         check_added_monitors!(nodes[0], 1);
280
281         let events_2 = nodes[0].node.get_and_clear_pending_events();
282         assert_eq!(events_2.len(), 1);
283         match events_2[0] {
284                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
285                 _ => panic!("Unexpected event"),
286         }
287
288         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
289         check_added_monitors!(nodes[1], 1);
290 }
291
292 #[test]
293 fn test_update_fee_unordered_raa() {
294         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
295         // crash in an earlier version of the update_fee patch)
296         let chanmon_cfgs = create_chanmon_cfgs(2);
297         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
298         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
299         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
300         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
301
302         // balancing
303         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
304
305         // First nodes[0] generates an update_fee
306         {
307                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
308                 *feerate_lock += 20;
309         }
310         nodes[0].node.timer_tick_occurred();
311         check_added_monitors!(nodes[0], 1);
312
313         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
314         assert_eq!(events_0.len(), 1);
315         let update_msg = match events_0[0] { // (1)
316                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
317                         update_fee.as_ref()
318                 },
319                 _ => panic!("Unexpected event"),
320         };
321
322         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
323
324         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
325         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
326         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
327         check_added_monitors!(nodes[1], 1);
328
329         let payment_event = {
330                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
331                 assert_eq!(events_1.len(), 1);
332                 SendEvent::from_event(events_1.remove(0))
333         };
334         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
335         assert_eq!(payment_event.msgs.len(), 1);
336
337         // ...now when the messages get delivered everyone should be happy
338         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
339         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
340         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
341         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
342         check_added_monitors!(nodes[0], 1);
343
344         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
345         check_added_monitors!(nodes[1], 1);
346
347         // We can't continue, sadly, because our (1) now has a bogus signature
348 }
349
350 #[test]
351 fn test_multi_flight_update_fee() {
352         let chanmon_cfgs = create_chanmon_cfgs(2);
353         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
354         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
355         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
356         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
357
358         // A                                        B
359         // update_fee/commitment_signed          ->
360         //                                       .- send (1) RAA and (2) commitment_signed
361         // update_fee (never committed)          ->
362         // (3) update_fee                        ->
363         // We have to manually generate the above update_fee, it is allowed by the protocol but we
364         // don't track which updates correspond to which revoke_and_ack responses so we're in
365         // AwaitingRAA mode and will not generate the update_fee yet.
366         //                                       <- (1) RAA delivered
367         // (3) is generated and send (4) CS      -.
368         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
369         // know the per_commitment_point to use for it.
370         //                                       <- (2) commitment_signed delivered
371         // revoke_and_ack                        ->
372         //                                          B should send no response here
373         // (4) commitment_signed delivered       ->
374         //                                       <- RAA/commitment_signed delivered
375         // revoke_and_ack                        ->
376
377         // First nodes[0] generates an update_fee
378         let initial_feerate;
379         {
380                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
381                 initial_feerate = *feerate_lock;
382                 *feerate_lock = initial_feerate + 20;
383         }
384         nodes[0].node.timer_tick_occurred();
385         check_added_monitors!(nodes[0], 1);
386
387         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
388         assert_eq!(events_0.len(), 1);
389         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
390                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
391                         (update_fee.as_ref().unwrap(), commitment_signed)
392                 },
393                 _ => panic!("Unexpected event"),
394         };
395
396         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
397         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
398         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
399         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
400         check_added_monitors!(nodes[1], 1);
401
402         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
403         // transaction:
404         {
405                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
406                 *feerate_lock = initial_feerate + 40;
407         }
408         nodes[0].node.timer_tick_occurred();
409         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
410         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
411
412         // Create the (3) update_fee message that nodes[0] will generate before it does...
413         let mut update_msg_2 = msgs::UpdateFee {
414                 channel_id: update_msg_1.channel_id.clone(),
415                 feerate_per_kw: (initial_feerate + 30) as u32,
416         };
417
418         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
419
420         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
421         // Deliver (3)
422         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
423
424         // Deliver (1), generating (3) and (4)
425         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
426         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
427         check_added_monitors!(nodes[0], 1);
428         assert!(as_second_update.update_add_htlcs.is_empty());
429         assert!(as_second_update.update_fulfill_htlcs.is_empty());
430         assert!(as_second_update.update_fail_htlcs.is_empty());
431         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
432         // Check that the update_fee newly generated matches what we delivered:
433         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
434         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
435
436         // Deliver (2) commitment_signed
437         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
438         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
439         check_added_monitors!(nodes[0], 1);
440         // No commitment_signed so get_event_msg's assert(len == 1) passes
441
442         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
443         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
444         check_added_monitors!(nodes[1], 1);
445
446         // Delever (4)
447         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
448         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
449         check_added_monitors!(nodes[1], 1);
450
451         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
452         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
453         check_added_monitors!(nodes[0], 1);
454
455         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
456         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
457         // No commitment_signed so get_event_msg's assert(len == 1) passes
458         check_added_monitors!(nodes[0], 1);
459
460         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
461         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
462         check_added_monitors!(nodes[1], 1);
463 }
464
465 fn do_test_sanity_on_in_flight_opens(steps: u8) {
466         // Previously, we had issues deserializing channels when we hadn't connected the first block
467         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
468         // serialization round-trips and simply do steps towards opening a channel and then drop the
469         // Node objects.
470
471         let chanmon_cfgs = create_chanmon_cfgs(2);
472         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
473         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
474         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
475
476         if steps & 0b1000_0000 != 0{
477                 let block = Block {
478                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
479                         txdata: vec![],
480                 };
481                 connect_block(&nodes[0], &block);
482                 connect_block(&nodes[1], &block);
483         }
484
485         if steps & 0x0f == 0 { return; }
486         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
487         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
488
489         if steps & 0x0f == 1 { return; }
490         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
491         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
492
493         if steps & 0x0f == 2 { return; }
494         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
495
496         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
497
498         if steps & 0x0f == 3 { return; }
499         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
500         check_added_monitors!(nodes[0], 0);
501         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
502
503         if steps & 0x0f == 4 { return; }
504         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
505         {
506                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
507                 assert_eq!(added_monitors.len(), 1);
508                 assert_eq!(added_monitors[0].0, funding_output);
509                 added_monitors.clear();
510         }
511         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
512
513         if steps & 0x0f == 5 { return; }
514         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
515         {
516                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
517                 assert_eq!(added_monitors.len(), 1);
518                 assert_eq!(added_monitors[0].0, funding_output);
519                 added_monitors.clear();
520         }
521
522         let events_4 = nodes[0].node.get_and_clear_pending_events();
523         assert_eq!(events_4.len(), 0);
524
525         if steps & 0x0f == 6 { return; }
526         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
527
528         if steps & 0x0f == 7 { return; }
529         confirm_transaction_at(&nodes[0], &tx, 2);
530         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
531         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
532 }
533
534 #[test]
535 fn test_sanity_on_in_flight_opens() {
536         do_test_sanity_on_in_flight_opens(0);
537         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
538         do_test_sanity_on_in_flight_opens(1);
539         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
540         do_test_sanity_on_in_flight_opens(2);
541         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
542         do_test_sanity_on_in_flight_opens(3);
543         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
544         do_test_sanity_on_in_flight_opens(4);
545         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
546         do_test_sanity_on_in_flight_opens(5);
547         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
548         do_test_sanity_on_in_flight_opens(6);
549         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
550         do_test_sanity_on_in_flight_opens(7);
551         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
552         do_test_sanity_on_in_flight_opens(8);
553         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
554 }
555
556 #[test]
557 fn test_update_fee_vanilla() {
558         let chanmon_cfgs = create_chanmon_cfgs(2);
559         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
560         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
561         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
562         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
563
564         {
565                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
566                 *feerate_lock += 25;
567         }
568         nodes[0].node.timer_tick_occurred();
569         check_added_monitors!(nodes[0], 1);
570
571         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
572         assert_eq!(events_0.len(), 1);
573         let (update_msg, commitment_signed) = match events_0[0] {
574                         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 } } => {
575                         (update_fee.as_ref(), commitment_signed)
576                 },
577                 _ => panic!("Unexpected event"),
578         };
579         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
580
581         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
582         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
583         check_added_monitors!(nodes[1], 1);
584
585         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
586         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
587         check_added_monitors!(nodes[0], 1);
588
589         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
590         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
591         // No commitment_signed so get_event_msg's assert(len == 1) passes
592         check_added_monitors!(nodes[0], 1);
593
594         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
595         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
596         check_added_monitors!(nodes[1], 1);
597 }
598
599 #[test]
600 fn test_update_fee_that_funder_cannot_afford() {
601         let chanmon_cfgs = create_chanmon_cfgs(2);
602         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
603         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
604         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
605         let channel_value = 5000;
606         let push_sats = 700;
607         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
608         let channel_id = chan.2;
609         let secp_ctx = Secp256k1::new();
610         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
611
612         let opt_anchors = false;
613
614         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
615         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
616         // calculate two different feerates here - the expected local limit as well as the expected
617         // remote limit.
618         let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
619         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
620         {
621                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
622                 *feerate_lock = feerate;
623         }
624         nodes[0].node.timer_tick_occurred();
625         check_added_monitors!(nodes[0], 1);
626         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
627
628         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
629
630         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
631
632         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
633         {
634                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
635
636                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
637                 assert_eq!(commitment_tx.output.len(), 2);
638                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
639                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
640                 actual_fee = channel_value - actual_fee;
641                 assert_eq!(total_fee, actual_fee);
642         }
643
644         {
645                 // Increment the feerate by a small constant, accounting for rounding errors
646                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
647                 *feerate_lock += 4;
648         }
649         nodes[0].node.timer_tick_occurred();
650         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
651         check_added_monitors!(nodes[0], 0);
652
653         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
654
655         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
656         // needed to sign the new commitment tx and (2) sign the new commitment tx.
657         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
658                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
659                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
660                 let chan_signer = local_chan.get_signer();
661                 let pubkeys = chan_signer.pubkeys();
662                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
663                  pubkeys.funding_pubkey)
664         };
665         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
666                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
667                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
668                 let chan_signer = remote_chan.get_signer();
669                 let pubkeys = chan_signer.pubkeys();
670                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
671                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
672                  pubkeys.funding_pubkey)
673         };
674
675         // Assemble the set of keys we can use for signatures for our commitment_signed message.
676         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
677                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
678
679         let res = {
680                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
681                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
682                 let local_chan_signer = local_chan.get_signer();
683                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
684                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
685                         INITIAL_COMMITMENT_NUMBER - 1,
686                         push_sats,
687                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
688                         opt_anchors, local_funding, remote_funding,
689                         commit_tx_keys.clone(),
690                         non_buffer_feerate + 4,
691                         &mut htlcs,
692                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
693                 );
694                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
695         };
696
697         let commit_signed_msg = msgs::CommitmentSigned {
698                 channel_id: chan.2,
699                 signature: res.0,
700                 htlc_signatures: res.1
701         };
702
703         let update_fee = msgs::UpdateFee {
704                 channel_id: chan.2,
705                 feerate_per_kw: non_buffer_feerate + 4,
706         };
707
708         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
709
710         //While producing the commitment_signed response after handling a received update_fee request the
711         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
712         //Should produce and error.
713         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
714         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
715         check_added_monitors!(nodes[1], 1);
716         check_closed_broadcast!(nodes[1], true);
717         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
718 }
719
720 #[test]
721 fn test_update_fee_with_fundee_update_add_htlc() {
722         let chanmon_cfgs = create_chanmon_cfgs(2);
723         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
724         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
725         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
726         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
727
728         // balancing
729         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
730
731         {
732                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
733                 *feerate_lock += 20;
734         }
735         nodes[0].node.timer_tick_occurred();
736         check_added_monitors!(nodes[0], 1);
737
738         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
739         assert_eq!(events_0.len(), 1);
740         let (update_msg, commitment_signed) = match events_0[0] {
741                         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 } } => {
742                         (update_fee.as_ref(), commitment_signed)
743                 },
744                 _ => panic!("Unexpected event"),
745         };
746         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
747         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
748         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
749         check_added_monitors!(nodes[1], 1);
750
751         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
752
753         // nothing happens since node[1] is in AwaitingRemoteRevoke
754         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
755         {
756                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
757                 assert_eq!(added_monitors.len(), 0);
758                 added_monitors.clear();
759         }
760         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
761         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
762         // node[1] has nothing to do
763
764         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
765         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
766         check_added_monitors!(nodes[0], 1);
767
768         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
769         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
770         // No commitment_signed so get_event_msg's assert(len == 1) passes
771         check_added_monitors!(nodes[0], 1);
772         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
773         check_added_monitors!(nodes[1], 1);
774         // AwaitingRemoteRevoke ends here
775
776         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
777         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
778         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
779         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
780         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
781         assert_eq!(commitment_update.update_fee.is_none(), true);
782
783         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
784         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
785         check_added_monitors!(nodes[0], 1);
786         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
787
788         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
789         check_added_monitors!(nodes[1], 1);
790         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
791
792         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
793         check_added_monitors!(nodes[1], 1);
794         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
795         // No commitment_signed so get_event_msg's assert(len == 1) passes
796
797         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
798         check_added_monitors!(nodes[0], 1);
799         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
800
801         expect_pending_htlcs_forwardable!(nodes[0]);
802
803         let events = nodes[0].node.get_and_clear_pending_events();
804         assert_eq!(events.len(), 1);
805         match events[0] {
806                 Event::PaymentReceived { .. } => { },
807                 _ => panic!("Unexpected event"),
808         };
809
810         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
811
812         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
813         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
814         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
815         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
816         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
817 }
818
819 #[test]
820 fn test_update_fee() {
821         let chanmon_cfgs = create_chanmon_cfgs(2);
822         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
823         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
824         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
825         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
826         let channel_id = chan.2;
827
828         // A                                        B
829         // (1) update_fee/commitment_signed      ->
830         //                                       <- (2) revoke_and_ack
831         //                                       .- send (3) commitment_signed
832         // (4) update_fee/commitment_signed      ->
833         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
834         //                                       <- (3) commitment_signed delivered
835         // send (6) revoke_and_ack               -.
836         //                                       <- (5) deliver revoke_and_ack
837         // (6) deliver revoke_and_ack            ->
838         //                                       .- send (7) commitment_signed in response to (4)
839         //                                       <- (7) deliver commitment_signed
840         // revoke_and_ack                        ->
841
842         // Create and deliver (1)...
843         let feerate;
844         {
845                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
846                 feerate = *feerate_lock;
847                 *feerate_lock = feerate + 20;
848         }
849         nodes[0].node.timer_tick_occurred();
850         check_added_monitors!(nodes[0], 1);
851
852         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
853         assert_eq!(events_0.len(), 1);
854         let (update_msg, commitment_signed) = match events_0[0] {
855                         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 } } => {
856                         (update_fee.as_ref(), commitment_signed)
857                 },
858                 _ => panic!("Unexpected event"),
859         };
860         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
861
862         // Generate (2) and (3):
863         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
864         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
865         check_added_monitors!(nodes[1], 1);
866
867         // Deliver (2):
868         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
869         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
870         check_added_monitors!(nodes[0], 1);
871
872         // Create and deliver (4)...
873         {
874                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
875                 *feerate_lock = feerate + 30;
876         }
877         nodes[0].node.timer_tick_occurred();
878         check_added_monitors!(nodes[0], 1);
879         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
880         assert_eq!(events_0.len(), 1);
881         let (update_msg, commitment_signed) = match events_0[0] {
882                         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 } } => {
883                         (update_fee.as_ref(), commitment_signed)
884                 },
885                 _ => panic!("Unexpected event"),
886         };
887
888         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
889         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
890         check_added_monitors!(nodes[1], 1);
891         // ... creating (5)
892         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
893         // No commitment_signed so get_event_msg's assert(len == 1) passes
894
895         // Handle (3), creating (6):
896         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
897         check_added_monitors!(nodes[0], 1);
898         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
899         // No commitment_signed so get_event_msg's assert(len == 1) passes
900
901         // Deliver (5):
902         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
903         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
904         check_added_monitors!(nodes[0], 1);
905
906         // Deliver (6), creating (7):
907         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
908         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
909         assert!(commitment_update.update_add_htlcs.is_empty());
910         assert!(commitment_update.update_fulfill_htlcs.is_empty());
911         assert!(commitment_update.update_fail_htlcs.is_empty());
912         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
913         assert!(commitment_update.update_fee.is_none());
914         check_added_monitors!(nodes[1], 1);
915
916         // Deliver (7)
917         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
918         check_added_monitors!(nodes[0], 1);
919         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
920         // No commitment_signed so get_event_msg's assert(len == 1) passes
921
922         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
923         check_added_monitors!(nodes[1], 1);
924         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
925
926         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
927         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
928         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
929         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
930         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
931 }
932
933 #[test]
934 fn fake_network_test() {
935         // Simple test which builds a network of ChannelManagers, connects them to each other, and
936         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
937         let chanmon_cfgs = create_chanmon_cfgs(4);
938         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
939         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
940         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
941
942         // Create some initial channels
943         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
944         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
945         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
946
947         // Rebalance the network a bit by relaying one payment through all the channels...
948         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
949         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
950         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
951         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
952
953         // Send some more payments
954         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
955         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
956         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
957
958         // Test failure packets
959         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
960         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
961
962         // Add a new channel that skips 3
963         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
964
965         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
966         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
967         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
968         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
969         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
970         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
971         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
972
973         // Do some rebalance loop payments, simultaneously
974         let mut hops = Vec::with_capacity(3);
975         hops.push(RouteHop {
976                 pubkey: nodes[2].node.get_our_node_id(),
977                 node_features: NodeFeatures::empty(),
978                 short_channel_id: chan_2.0.contents.short_channel_id,
979                 channel_features: ChannelFeatures::empty(),
980                 fee_msat: 0,
981                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
982         });
983         hops.push(RouteHop {
984                 pubkey: nodes[3].node.get_our_node_id(),
985                 node_features: NodeFeatures::empty(),
986                 short_channel_id: chan_3.0.contents.short_channel_id,
987                 channel_features: ChannelFeatures::empty(),
988                 fee_msat: 0,
989                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
990         });
991         hops.push(RouteHop {
992                 pubkey: nodes[1].node.get_our_node_id(),
993                 node_features: NodeFeatures::known(),
994                 short_channel_id: chan_4.0.contents.short_channel_id,
995                 channel_features: ChannelFeatures::known(),
996                 fee_msat: 1000000,
997                 cltv_expiry_delta: TEST_FINAL_CLTV,
998         });
999         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;
1000         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;
1001         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1002
1003         let mut hops = Vec::with_capacity(3);
1004         hops.push(RouteHop {
1005                 pubkey: nodes[3].node.get_our_node_id(),
1006                 node_features: NodeFeatures::empty(),
1007                 short_channel_id: chan_4.0.contents.short_channel_id,
1008                 channel_features: ChannelFeatures::empty(),
1009                 fee_msat: 0,
1010                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1011         });
1012         hops.push(RouteHop {
1013                 pubkey: nodes[2].node.get_our_node_id(),
1014                 node_features: NodeFeatures::empty(),
1015                 short_channel_id: chan_3.0.contents.short_channel_id,
1016                 channel_features: ChannelFeatures::empty(),
1017                 fee_msat: 0,
1018                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1019         });
1020         hops.push(RouteHop {
1021                 pubkey: nodes[1].node.get_our_node_id(),
1022                 node_features: NodeFeatures::known(),
1023                 short_channel_id: chan_2.0.contents.short_channel_id,
1024                 channel_features: ChannelFeatures::known(),
1025                 fee_msat: 1000000,
1026                 cltv_expiry_delta: TEST_FINAL_CLTV,
1027         });
1028         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;
1029         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;
1030         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1031
1032         // Claim the rebalances...
1033         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1034         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1035
1036         // Add a duplicate new channel from 2 to 4
1037         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1038
1039         // Send some payments across both channels
1040         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1041         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1042         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1043
1044
1045         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1046         let events = nodes[0].node.get_and_clear_pending_msg_events();
1047         assert_eq!(events.len(), 0);
1048         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);
1049
1050         //TODO: Test that routes work again here as we've been notified that the channel is full
1051
1052         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1053         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1054         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1055
1056         // Close down the channels...
1057         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1058         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1059         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1060         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1061         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1062         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1063         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1064         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1065         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1066         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1067         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1068         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1069         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1070         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1071         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1072 }
1073
1074 #[test]
1075 fn holding_cell_htlc_counting() {
1076         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1077         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1078         // commitment dance rounds.
1079         let chanmon_cfgs = create_chanmon_cfgs(3);
1080         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1081         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1082         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1083         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1084         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1085
1086         let mut payments = Vec::new();
1087         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1088                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1089                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1090                 payments.push((payment_preimage, payment_hash));
1091         }
1092         check_added_monitors!(nodes[1], 1);
1093
1094         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1095         assert_eq!(events.len(), 1);
1096         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1097         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1098
1099         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1100         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1101         // another HTLC.
1102         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1103         {
1104                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1105                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1106                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1107                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1108         }
1109
1110         // This should also be true if we try to forward a payment.
1111         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1112         {
1113                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1114                 check_added_monitors!(nodes[0], 1);
1115         }
1116
1117         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1118         assert_eq!(events.len(), 1);
1119         let payment_event = SendEvent::from_event(events.pop().unwrap());
1120         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1121
1122         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1123         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1124         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1125         // fails), the second will process the resulting failure and fail the HTLC backward.
1126         expect_pending_htlcs_forwardable!(nodes[1]);
1127         expect_pending_htlcs_forwardable!(nodes[1]);
1128         check_added_monitors!(nodes[1], 1);
1129
1130         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1131         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1132         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1133
1134         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1135
1136         // Now forward all the pending HTLCs and claim them back
1137         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1138         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1139         check_added_monitors!(nodes[2], 1);
1140
1141         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1142         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1143         check_added_monitors!(nodes[1], 1);
1144         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1145
1146         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1147         check_added_monitors!(nodes[1], 1);
1148         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1149
1150         for ref update in as_updates.update_add_htlcs.iter() {
1151                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1152         }
1153         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1154         check_added_monitors!(nodes[2], 1);
1155         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1156         check_added_monitors!(nodes[2], 1);
1157         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1158
1159         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1160         check_added_monitors!(nodes[1], 1);
1161         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1162         check_added_monitors!(nodes[1], 1);
1163         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1164
1165         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1166         check_added_monitors!(nodes[2], 1);
1167
1168         expect_pending_htlcs_forwardable!(nodes[2]);
1169
1170         let events = nodes[2].node.get_and_clear_pending_events();
1171         assert_eq!(events.len(), payments.len());
1172         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1173                 match event {
1174                         &Event::PaymentReceived { ref payment_hash, .. } => {
1175                                 assert_eq!(*payment_hash, *hash);
1176                         },
1177                         _ => panic!("Unexpected event"),
1178                 };
1179         }
1180
1181         for (preimage, _) in payments.drain(..) {
1182                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1183         }
1184
1185         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1186 }
1187
1188 #[test]
1189 fn duplicate_htlc_test() {
1190         // Test that we accept duplicate payment_hash HTLCs across the network and that
1191         // claiming/failing them are all separate and don't affect each other
1192         let chanmon_cfgs = create_chanmon_cfgs(6);
1193         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1194         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1195         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1196
1197         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1198         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1199         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1200         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1201         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1202         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1203
1204         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1205
1206         *nodes[0].network_payment_count.borrow_mut() -= 1;
1207         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1208
1209         *nodes[0].network_payment_count.borrow_mut() -= 1;
1210         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1211
1212         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1213         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1214         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1215 }
1216
1217 #[test]
1218 fn test_duplicate_htlc_different_direction_onchain() {
1219         // Test that ChannelMonitor doesn't generate 2 preimage txn
1220         // when we have 2 HTLCs with same preimage that go across a node
1221         // in opposite directions, even with the same payment secret.
1222         let chanmon_cfgs = create_chanmon_cfgs(2);
1223         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1224         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1225         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1226
1227         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1228
1229         // balancing
1230         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1231
1232         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1233
1234         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1235         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1236         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1237
1238         // Provide preimage to node 0 by claiming payment
1239         nodes[0].node.claim_funds(payment_preimage);
1240         check_added_monitors!(nodes[0], 1);
1241
1242         // Broadcast node 1 commitment txn
1243         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1244
1245         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1246         let mut has_both_htlcs = 0; // check htlcs match ones committed
1247         for outp in remote_txn[0].output.iter() {
1248                 if outp.value == 800_000 / 1000 {
1249                         has_both_htlcs += 1;
1250                 } else if outp.value == 900_000 / 1000 {
1251                         has_both_htlcs += 1;
1252                 }
1253         }
1254         assert_eq!(has_both_htlcs, 2);
1255
1256         mine_transaction(&nodes[0], &remote_txn[0]);
1257         check_added_monitors!(nodes[0], 1);
1258         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1259         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1260
1261         // Check we only broadcast 1 timeout tx
1262         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1263         assert_eq!(claim_txn.len(), 8);
1264         assert_eq!(claim_txn[1], claim_txn[4]);
1265         assert_eq!(claim_txn[2], claim_txn[5]);
1266         check_spends!(claim_txn[1], chan_1.3);
1267         check_spends!(claim_txn[2], claim_txn[1]);
1268         check_spends!(claim_txn[7], claim_txn[1]);
1269
1270         assert_eq!(claim_txn[0].input.len(), 1);
1271         assert_eq!(claim_txn[3].input.len(), 1);
1272         assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1273
1274         assert_eq!(claim_txn[0].input.len(), 1);
1275         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1276         check_spends!(claim_txn[0], remote_txn[0]);
1277         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1278         assert_eq!(claim_txn[6].input.len(), 1);
1279         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1280         check_spends!(claim_txn[6], remote_txn[0]);
1281         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1282
1283         let events = nodes[0].node.get_and_clear_pending_msg_events();
1284         assert_eq!(events.len(), 3);
1285         for e in events {
1286                 match e {
1287                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1288                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1289                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1290                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1291                         },
1292                         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, .. } } => {
1293                                 assert!(update_add_htlcs.is_empty());
1294                                 assert!(update_fail_htlcs.is_empty());
1295                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1296                                 assert!(update_fail_malformed_htlcs.is_empty());
1297                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1298                         },
1299                         _ => panic!("Unexpected event"),
1300                 }
1301         }
1302 }
1303
1304 #[test]
1305 fn test_basic_channel_reserve() {
1306         let chanmon_cfgs = create_chanmon_cfgs(2);
1307         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1308         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1309         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1310         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1311
1312         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1313         let channel_reserve = chan_stat.channel_reserve_msat;
1314
1315         // The 2* and +1 are for the fee spike reserve.
1316         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1317         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1318         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1319         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1320         match err {
1321                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1322                         match &fails[0] {
1323                                 &APIError::ChannelUnavailable{ref err} =>
1324                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1325                                 _ => panic!("Unexpected error variant"),
1326                         }
1327                 },
1328                 _ => panic!("Unexpected error variant"),
1329         }
1330         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1331         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);
1332
1333         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1334 }
1335
1336 #[test]
1337 fn test_fee_spike_violation_fails_htlc() {
1338         let chanmon_cfgs = create_chanmon_cfgs(2);
1339         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1340         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1341         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1342         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1343
1344         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1345         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1346         let secp_ctx = Secp256k1::new();
1347         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1348
1349         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1350
1351         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1352         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1353         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1354         let msg = msgs::UpdateAddHTLC {
1355                 channel_id: chan.2,
1356                 htlc_id: 0,
1357                 amount_msat: htlc_msat,
1358                 payment_hash: payment_hash,
1359                 cltv_expiry: htlc_cltv,
1360                 onion_routing_packet: onion_packet,
1361         };
1362
1363         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1364
1365         // Now manually create the commitment_signed message corresponding to the update_add
1366         // nodes[0] just sent. In the code for construction of this message, "local" refers
1367         // to the sender of the message, and "remote" refers to the receiver.
1368
1369         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1370
1371         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1372
1373         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1374         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1375         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1376                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1377                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1378                 let chan_signer = local_chan.get_signer();
1379                 // Make the signer believe we validated another commitment, so we can release the secret
1380                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1381
1382                 let pubkeys = chan_signer.pubkeys();
1383                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1384                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1385                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1386                  chan_signer.pubkeys().funding_pubkey)
1387         };
1388         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1389                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1390                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1391                 let chan_signer = remote_chan.get_signer();
1392                 let pubkeys = chan_signer.pubkeys();
1393                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1394                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1395                  chan_signer.pubkeys().funding_pubkey)
1396         };
1397
1398         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1399         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1400                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1401
1402         // Build the remote commitment transaction so we can sign it, and then later use the
1403         // signature for the commitment_signed message.
1404         let local_chan_balance = 1313;
1405
1406         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1407                 offered: false,
1408                 amount_msat: 3460001,
1409                 cltv_expiry: htlc_cltv,
1410                 payment_hash,
1411                 transaction_output_index: Some(1),
1412         };
1413
1414         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1415
1416         let res = {
1417                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1418                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1419                 let local_chan_signer = local_chan.get_signer();
1420                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1421                         commitment_number,
1422                         95000,
1423                         local_chan_balance,
1424                         local_chan.opt_anchors(), local_funding, remote_funding,
1425                         commit_tx_keys.clone(),
1426                         feerate_per_kw,
1427                         &mut vec![(accepted_htlc_info, ())],
1428                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1429                 );
1430                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1431         };
1432
1433         let commit_signed_msg = msgs::CommitmentSigned {
1434                 channel_id: chan.2,
1435                 signature: res.0,
1436                 htlc_signatures: res.1
1437         };
1438
1439         // Send the commitment_signed message to the nodes[1].
1440         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1441         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1442
1443         // Send the RAA to nodes[1].
1444         let raa_msg = msgs::RevokeAndACK {
1445                 channel_id: chan.2,
1446                 per_commitment_secret: local_secret,
1447                 next_per_commitment_point: next_local_point
1448         };
1449         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1450
1451         let events = nodes[1].node.get_and_clear_pending_msg_events();
1452         assert_eq!(events.len(), 1);
1453         // Make sure the HTLC failed in the way we expect.
1454         match events[0] {
1455                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1456                         assert_eq!(update_fail_htlcs.len(), 1);
1457                         update_fail_htlcs[0].clone()
1458                 },
1459                 _ => panic!("Unexpected event"),
1460         };
1461         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1462                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1463
1464         check_added_monitors!(nodes[1], 2);
1465 }
1466
1467 #[test]
1468 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1469         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1470         // Set the fee rate for the channel very high, to the point where the fundee
1471         // sending any above-dust amount would result in a channel reserve violation.
1472         // In this test we check that we would be prevented from sending an HTLC in
1473         // this situation.
1474         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1475         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1476         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1477         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1478
1479         let opt_anchors = false;
1480
1481         let mut push_amt = 100_000_000;
1482         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1483         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1484
1485         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1486
1487         // Sending exactly enough to hit the reserve amount should be accepted
1488         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1489                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1490         }
1491
1492         // However one more HTLC should be significantly over the reserve amount and fail.
1493         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1494         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1495                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1496         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1497         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);
1498 }
1499
1500 #[test]
1501 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1502         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1503         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1504         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1505         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1506         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1507
1508         let opt_anchors = false;
1509
1510         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1511         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1512         // transaction fee with 0 HTLCs (183 sats)).
1513         let mut push_amt = 100_000_000;
1514         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1515         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1516         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1517
1518         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1519         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1520                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1521         }
1522
1523         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1524         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1525         let secp_ctx = Secp256k1::new();
1526         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1527         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1528         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1529         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1530         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1531         let msg = msgs::UpdateAddHTLC {
1532                 channel_id: chan.2,
1533                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1534                 amount_msat: htlc_msat,
1535                 payment_hash: payment_hash,
1536                 cltv_expiry: htlc_cltv,
1537                 onion_routing_packet: onion_packet,
1538         };
1539
1540         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1541         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1542         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);
1543         assert_eq!(nodes[0].node.list_channels().len(), 0);
1544         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1545         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1546         check_added_monitors!(nodes[0], 1);
1547         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() });
1548 }
1549
1550 #[test]
1551 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1552         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1553         // calculating our commitment transaction fee (this was previously broken).
1554         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1555         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1556
1557         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1558         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1559         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1560
1561         let opt_anchors = false;
1562
1563         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1564         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1565         // transaction fee with 0 HTLCs (183 sats)).
1566         let mut push_amt = 100_000_000;
1567         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1568         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1569         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1570
1571         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1572                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1573         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1574         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1575         // commitment transaction fee.
1576         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1577
1578         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1579         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1580                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1581         }
1582
1583         // One more than the dust amt should fail, however.
1584         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1585         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1586                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1587 }
1588
1589 #[test]
1590 fn test_chan_init_feerate_unaffordability() {
1591         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1592         // channel reserve and feerate requirements.
1593         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1594         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1595         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1596         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1597         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1598
1599         let opt_anchors = false;
1600
1601         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1602         // HTLC.
1603         let mut push_amt = 100_000_000;
1604         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1605         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1606                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1607
1608         // During open, we don't have a "counterparty channel reserve" to check against, so that
1609         // requirement only comes into play on the open_channel handling side.
1610         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1611         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1612         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1613         open_channel_msg.push_msat += 1;
1614         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1615
1616         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1617         assert_eq!(msg_events.len(), 1);
1618         match msg_events[0] {
1619                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1620                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1621                 },
1622                 _ => panic!("Unexpected event"),
1623         }
1624 }
1625
1626 #[test]
1627 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1628         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1629         // calculating our counterparty's commitment transaction fee (this was previously broken).
1630         let chanmon_cfgs = create_chanmon_cfgs(2);
1631         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1632         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1633         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1634         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1635
1636         let payment_amt = 46000; // Dust amount
1637         // In the previous code, these first four payments would succeed.
1638         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1639         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1640         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1641         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1642
1643         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1644         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1645         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1646         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1647         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1648         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1649
1650         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1651         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1652         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1653         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1654 }
1655
1656 #[test]
1657 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1658         let chanmon_cfgs = create_chanmon_cfgs(3);
1659         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1660         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1661         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1662         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1663         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1664
1665         let feemsat = 239;
1666         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1667         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1668         let feerate = get_feerate!(nodes[0], chan.2);
1669         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1670
1671         // Add a 2* and +1 for the fee spike reserve.
1672         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1673         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;
1674         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1675
1676         // Add a pending HTLC.
1677         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1678         let payment_event_1 = {
1679                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1680                 check_added_monitors!(nodes[0], 1);
1681
1682                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1683                 assert_eq!(events.len(), 1);
1684                 SendEvent::from_event(events.remove(0))
1685         };
1686         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1687
1688         // Attempt to trigger a channel reserve violation --> payment failure.
1689         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1690         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;
1691         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1692         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1693
1694         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1695         let secp_ctx = Secp256k1::new();
1696         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1697         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1698         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1699         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1700         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1701         let msg = msgs::UpdateAddHTLC {
1702                 channel_id: chan.2,
1703                 htlc_id: 1,
1704                 amount_msat: htlc_msat + 1,
1705                 payment_hash: our_payment_hash_1,
1706                 cltv_expiry: htlc_cltv,
1707                 onion_routing_packet: onion_packet,
1708         };
1709
1710         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1711         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1712         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1713         assert_eq!(nodes[1].node.list_channels().len(), 1);
1714         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1715         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1716         check_added_monitors!(nodes[1], 1);
1717         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1718 }
1719
1720 #[test]
1721 fn test_inbound_outbound_capacity_is_not_zero() {
1722         let chanmon_cfgs = create_chanmon_cfgs(2);
1723         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1724         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1725         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1726         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1727         let channels0 = node_chanmgrs[0].list_channels();
1728         let channels1 = node_chanmgrs[1].list_channels();
1729         assert_eq!(channels0.len(), 1);
1730         assert_eq!(channels1.len(), 1);
1731
1732         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1733         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1734         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1735
1736         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1737         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1738 }
1739
1740 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1741         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1742 }
1743
1744 #[test]
1745 fn test_channel_reserve_holding_cell_htlcs() {
1746         let chanmon_cfgs = create_chanmon_cfgs(3);
1747         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1748         // When this test was written, the default base fee floated based on the HTLC count.
1749         // It is now fixed, so we simply set the fee to the expected value here.
1750         let mut config = test_default_channel_config();
1751         config.channel_options.forwarding_fee_base_msat = 239;
1752         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1753         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1754         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1755         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1756
1757         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1758         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1759
1760         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1761         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1762
1763         macro_rules! expect_forward {
1764                 ($node: expr) => {{
1765                         let mut events = $node.node.get_and_clear_pending_msg_events();
1766                         assert_eq!(events.len(), 1);
1767                         check_added_monitors!($node, 1);
1768                         let payment_event = SendEvent::from_event(events.remove(0));
1769                         payment_event
1770                 }}
1771         }
1772
1773         let feemsat = 239; // set above
1774         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1775         let feerate = get_feerate!(nodes[0], chan_1.2);
1776         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1777
1778         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1779
1780         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1781         {
1782                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1783                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1784                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1785                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1786                         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)));
1787                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1788                 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);
1789         }
1790
1791         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1792         // nodes[0]'s wealth
1793         loop {
1794                 let amt_msat = recv_value_0 + total_fee_msat;
1795                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1796                 // Also, ensure that each payment has enough to be over the dust limit to
1797                 // ensure it'll be included in each commit tx fee calculation.
1798                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1799                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1800                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1801                         break;
1802                 }
1803                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1804
1805                 let (stat01_, stat11_, stat12_, stat22_) = (
1806                         get_channel_value_stat!(nodes[0], chan_1.2),
1807                         get_channel_value_stat!(nodes[1], chan_1.2),
1808                         get_channel_value_stat!(nodes[1], chan_2.2),
1809                         get_channel_value_stat!(nodes[2], chan_2.2),
1810                 );
1811
1812                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1813                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1814                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1815                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1816                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1817         }
1818
1819         // adding pending output.
1820         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1821         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1822         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1823         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1824         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1825         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1826         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1827         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1828         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1829         // policy.
1830         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1831         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1832         let amt_msat_1 = recv_value_1 + total_fee_msat;
1833
1834         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);
1835         let payment_event_1 = {
1836                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1837                 check_added_monitors!(nodes[0], 1);
1838
1839                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1840                 assert_eq!(events.len(), 1);
1841                 SendEvent::from_event(events.remove(0))
1842         };
1843         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1844
1845         // channel reserve test with htlc pending output > 0
1846         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1847         {
1848                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1849                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1850                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1851                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1852         }
1853
1854         // split the rest to test holding cell
1855         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1856         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1857         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1858         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1859         {
1860                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1861                 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);
1862         }
1863
1864         // now see if they go through on both sides
1865         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);
1866         // but this will stuck in the holding cell
1867         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1868         check_added_monitors!(nodes[0], 0);
1869         let events = nodes[0].node.get_and_clear_pending_events();
1870         assert_eq!(events.len(), 0);
1871
1872         // test with outbound holding cell amount > 0
1873         {
1874                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1875                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1876                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1877                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1878                 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);
1879         }
1880
1881         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);
1882         // this will also stuck in the holding cell
1883         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1884         check_added_monitors!(nodes[0], 0);
1885         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1886         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1887
1888         // flush the pending htlc
1889         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1890         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1891         check_added_monitors!(nodes[1], 1);
1892
1893         // the pending htlc should be promoted to committed
1894         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1895         check_added_monitors!(nodes[0], 1);
1896         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1897
1898         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1899         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1900         // No commitment_signed so get_event_msg's assert(len == 1) passes
1901         check_added_monitors!(nodes[0], 1);
1902
1903         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1904         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1905         check_added_monitors!(nodes[1], 1);
1906
1907         expect_pending_htlcs_forwardable!(nodes[1]);
1908
1909         let ref payment_event_11 = expect_forward!(nodes[1]);
1910         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1911         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1912
1913         expect_pending_htlcs_forwardable!(nodes[2]);
1914         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1915
1916         // flush the htlcs in the holding cell
1917         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1918         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1919         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1920         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1921         expect_pending_htlcs_forwardable!(nodes[1]);
1922
1923         let ref payment_event_3 = expect_forward!(nodes[1]);
1924         assert_eq!(payment_event_3.msgs.len(), 2);
1925         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1926         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1927
1928         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1929         expect_pending_htlcs_forwardable!(nodes[2]);
1930
1931         let events = nodes[2].node.get_and_clear_pending_events();
1932         assert_eq!(events.len(), 2);
1933         match events[0] {
1934                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1935                         assert_eq!(our_payment_hash_21, *payment_hash);
1936                         assert_eq!(recv_value_21, amt);
1937                         match &purpose {
1938                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1939                                         assert!(payment_preimage.is_none());
1940                                         assert_eq!(our_payment_secret_21, *payment_secret);
1941                                 },
1942                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1943                         }
1944                 },
1945                 _ => panic!("Unexpected event"),
1946         }
1947         match events[1] {
1948                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1949                         assert_eq!(our_payment_hash_22, *payment_hash);
1950                         assert_eq!(recv_value_22, amt);
1951                         match &purpose {
1952                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1953                                         assert!(payment_preimage.is_none());
1954                                         assert_eq!(our_payment_secret_22, *payment_secret);
1955                                 },
1956                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1957                         }
1958                 },
1959                 _ => panic!("Unexpected event"),
1960         }
1961
1962         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1963         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1964         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1965
1966         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1967         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1968         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1969
1970         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
1971         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);
1972         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1973         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1974         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1975
1976         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1977         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1978 }
1979
1980 #[test]
1981 fn channel_reserve_in_flight_removes() {
1982         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1983         // can send to its counterparty, but due to update ordering, the other side may not yet have
1984         // considered those HTLCs fully removed.
1985         // This tests that we don't count HTLCs which will not be included in the next remote
1986         // commitment transaction towards the reserve value (as it implies no commitment transaction
1987         // will be generated which violates the remote reserve value).
1988         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1989         // To test this we:
1990         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1991         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1992         //    you only consider the value of the first HTLC, it may not),
1993         //  * start routing a third HTLC from A to B,
1994         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1995         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1996         //  * deliver the first fulfill from B
1997         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1998         //    claim,
1999         //  * deliver A's response CS and RAA.
2000         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2001         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2002         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2003         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2004         let chanmon_cfgs = create_chanmon_cfgs(2);
2005         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2006         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2007         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2008         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2009
2010         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2011         // Route the first two HTLCs.
2012         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2013         let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2014
2015         // Start routing the third HTLC (this is just used to get everyone in the right state).
2016         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2017         let send_1 = {
2018                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2019                 check_added_monitors!(nodes[0], 1);
2020                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2021                 assert_eq!(events.len(), 1);
2022                 SendEvent::from_event(events.remove(0))
2023         };
2024
2025         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2026         // initial fulfill/CS.
2027         assert!(nodes[1].node.claim_funds(payment_preimage_1));
2028         check_added_monitors!(nodes[1], 1);
2029         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2030
2031         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2032         // remove the second HTLC when we send the HTLC back from B to A.
2033         assert!(nodes[1].node.claim_funds(payment_preimage_2));
2034         check_added_monitors!(nodes[1], 1);
2035         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2036
2037         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2038         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2039         check_added_monitors!(nodes[0], 1);
2040         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2041         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2042
2043         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2044         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2045         check_added_monitors!(nodes[1], 1);
2046         // B is already AwaitingRAA, so cant generate a CS here
2047         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2048
2049         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2050         check_added_monitors!(nodes[1], 1);
2051         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2052
2053         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2054         check_added_monitors!(nodes[0], 1);
2055         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2056
2057         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2058         check_added_monitors!(nodes[1], 1);
2059         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2060
2061         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2062         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2063         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2064         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2065         // on-chain as necessary).
2066         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2067         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2068         check_added_monitors!(nodes[0], 1);
2069         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2070         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2071
2072         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2073         check_added_monitors!(nodes[1], 1);
2074         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2075
2076         expect_pending_htlcs_forwardable!(nodes[1]);
2077         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2078
2079         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2080         // resolve the second HTLC from A's point of view.
2081         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2082         check_added_monitors!(nodes[0], 1);
2083         expect_payment_path_successful!(nodes[0]);
2084         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2085
2086         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2087         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2088         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2089         let send_2 = {
2090                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2091                 check_added_monitors!(nodes[1], 1);
2092                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2093                 assert_eq!(events.len(), 1);
2094                 SendEvent::from_event(events.remove(0))
2095         };
2096
2097         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2098         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2099         check_added_monitors!(nodes[0], 1);
2100         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2101
2102         // Now just resolve all the outstanding messages/HTLCs for completeness...
2103
2104         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2105         check_added_monitors!(nodes[1], 1);
2106         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2107
2108         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2109         check_added_monitors!(nodes[1], 1);
2110
2111         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2112         check_added_monitors!(nodes[0], 1);
2113         expect_payment_path_successful!(nodes[0]);
2114         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2115
2116         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2117         check_added_monitors!(nodes[1], 1);
2118         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2119
2120         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2121         check_added_monitors!(nodes[0], 1);
2122
2123         expect_pending_htlcs_forwardable!(nodes[0]);
2124         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2125
2126         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2127         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2128 }
2129
2130 #[test]
2131 fn channel_monitor_network_test() {
2132         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2133         // tests that ChannelMonitor is able to recover from various states.
2134         let chanmon_cfgs = create_chanmon_cfgs(5);
2135         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2136         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2137         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2138
2139         // Create some initial channels
2140         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2141         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2142         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2143         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2144
2145         // Make sure all nodes are at the same starting height
2146         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2147         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2148         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2149         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2150         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2151
2152         // Rebalance the network a bit by relaying one payment through all the channels...
2153         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2154         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2155         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2156         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2157
2158         // Simple case with no pending HTLCs:
2159         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2160         check_added_monitors!(nodes[1], 1);
2161         check_closed_broadcast!(nodes[1], false);
2162         {
2163                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2164                 assert_eq!(node_txn.len(), 1);
2165                 mine_transaction(&nodes[0], &node_txn[0]);
2166                 check_added_monitors!(nodes[0], 1);
2167                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2168         }
2169         check_closed_broadcast!(nodes[0], true);
2170         assert_eq!(nodes[0].node.list_channels().len(), 0);
2171         assert_eq!(nodes[1].node.list_channels().len(), 1);
2172         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2173         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2174
2175         // One pending HTLC is discarded by the force-close:
2176         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2177
2178         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2179         // broadcasted until we reach the timelock time).
2180         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2181         check_closed_broadcast!(nodes[1], false);
2182         check_added_monitors!(nodes[1], 1);
2183         {
2184                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2185                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2186                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2187                 mine_transaction(&nodes[2], &node_txn[0]);
2188                 check_added_monitors!(nodes[2], 1);
2189                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2190         }
2191         check_closed_broadcast!(nodes[2], true);
2192         assert_eq!(nodes[1].node.list_channels().len(), 0);
2193         assert_eq!(nodes[2].node.list_channels().len(), 1);
2194         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2195         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2196
2197         macro_rules! claim_funds {
2198                 ($node: expr, $prev_node: expr, $preimage: expr) => {
2199                         {
2200                                 assert!($node.node.claim_funds($preimage));
2201                                 check_added_monitors!($node, 1);
2202
2203                                 let events = $node.node.get_and_clear_pending_msg_events();
2204                                 assert_eq!(events.len(), 1);
2205                                 match events[0] {
2206                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2207                                                 assert!(update_add_htlcs.is_empty());
2208                                                 assert!(update_fail_htlcs.is_empty());
2209                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2210                                         },
2211                                         _ => panic!("Unexpected event"),
2212                                 };
2213                         }
2214                 }
2215         }
2216
2217         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2218         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2219         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2220         check_added_monitors!(nodes[2], 1);
2221         check_closed_broadcast!(nodes[2], false);
2222         let node2_commitment_txid;
2223         {
2224                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2225                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2226                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2227                 node2_commitment_txid = node_txn[0].txid();
2228
2229                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2230                 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2231                 mine_transaction(&nodes[3], &node_txn[0]);
2232                 check_added_monitors!(nodes[3], 1);
2233                 check_preimage_claim(&nodes[3], &node_txn);
2234         }
2235         check_closed_broadcast!(nodes[3], true);
2236         assert_eq!(nodes[2].node.list_channels().len(), 0);
2237         assert_eq!(nodes[3].node.list_channels().len(), 1);
2238         check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2239         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2240
2241         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2242         // confusing us in the following tests.
2243         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2244
2245         // One pending HTLC to time out:
2246         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2247         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2248         // buffer space).
2249
2250         let (close_chan_update_1, close_chan_update_2) = {
2251                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2252                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2253                 assert_eq!(events.len(), 2);
2254                 let close_chan_update_1 = match events[0] {
2255                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2256                                 msg.clone()
2257                         },
2258                         _ => panic!("Unexpected event"),
2259                 };
2260                 match events[1] {
2261                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2262                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2263                         },
2264                         _ => panic!("Unexpected event"),
2265                 }
2266                 check_added_monitors!(nodes[3], 1);
2267
2268                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2269                 {
2270                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2271                         node_txn.retain(|tx| {
2272                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2273                                         false
2274                                 } else { true }
2275                         });
2276                 }
2277
2278                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2279
2280                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2281                 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2282
2283                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2284                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2285                 assert_eq!(events.len(), 2);
2286                 let close_chan_update_2 = match events[0] {
2287                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2288                                 msg.clone()
2289                         },
2290                         _ => panic!("Unexpected event"),
2291                 };
2292                 match events[1] {
2293                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2294                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2295                         },
2296                         _ => panic!("Unexpected event"),
2297                 }
2298                 check_added_monitors!(nodes[4], 1);
2299                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2300
2301                 mine_transaction(&nodes[4], &node_txn[0]);
2302                 check_preimage_claim(&nodes[4], &node_txn);
2303                 (close_chan_update_1, close_chan_update_2)
2304         };
2305         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2306         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2307         assert_eq!(nodes[3].node.list_channels().len(), 0);
2308         assert_eq!(nodes[4].node.list_channels().len(), 0);
2309
2310         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2311         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2312         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2313 }
2314
2315 #[test]
2316 fn test_justice_tx() {
2317         // Test justice txn built on revoked HTLC-Success tx, against both sides
2318         let mut alice_config = UserConfig::default();
2319         alice_config.channel_options.announced_channel = true;
2320         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2321         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2322         let mut bob_config = UserConfig::default();
2323         bob_config.channel_options.announced_channel = true;
2324         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2325         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2326         let user_cfgs = [Some(alice_config), Some(bob_config)];
2327         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2328         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2329         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2330         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2331         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2332         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2333         // Create some new channels:
2334         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2335
2336         // A pending HTLC which will be revoked:
2337         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2338         // Get the will-be-revoked local txn from nodes[0]
2339         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2340         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2341         assert_eq!(revoked_local_txn[0].input.len(), 1);
2342         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2343         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2344         assert_eq!(revoked_local_txn[1].input.len(), 1);
2345         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2346         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2347         // Revoke the old state
2348         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2349
2350         {
2351                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2352                 {
2353                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2354                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2355                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2356
2357                         check_spends!(node_txn[0], revoked_local_txn[0]);
2358                         node_txn.swap_remove(0);
2359                         node_txn.truncate(1);
2360                 }
2361                 check_added_monitors!(nodes[1], 1);
2362                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2363                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2364
2365                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2366                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2367                 // Verify broadcast of revoked HTLC-timeout
2368                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2369                 check_added_monitors!(nodes[0], 1);
2370                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2371                 // Broadcast revoked HTLC-timeout on node 1
2372                 mine_transaction(&nodes[1], &node_txn[1]);
2373                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2374         }
2375         get_announce_close_broadcast_events(&nodes, 0, 1);
2376
2377         assert_eq!(nodes[0].node.list_channels().len(), 0);
2378         assert_eq!(nodes[1].node.list_channels().len(), 0);
2379
2380         // We test justice_tx build by A on B's revoked HTLC-Success tx
2381         // Create some new channels:
2382         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2383         {
2384                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2385                 node_txn.clear();
2386         }
2387
2388         // A pending HTLC which will be revoked:
2389         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2390         // Get the will-be-revoked local txn from B
2391         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2392         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2393         assert_eq!(revoked_local_txn[0].input.len(), 1);
2394         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2395         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2396         // Revoke the old state
2397         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2398         {
2399                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2400                 {
2401                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2402                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2403                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2404
2405                         check_spends!(node_txn[0], revoked_local_txn[0]);
2406                         node_txn.swap_remove(0);
2407                 }
2408                 check_added_monitors!(nodes[0], 1);
2409                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2410
2411                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2412                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2413                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2414                 check_added_monitors!(nodes[1], 1);
2415                 mine_transaction(&nodes[0], &node_txn[1]);
2416                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2417                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2418         }
2419         get_announce_close_broadcast_events(&nodes, 0, 1);
2420         assert_eq!(nodes[0].node.list_channels().len(), 0);
2421         assert_eq!(nodes[1].node.list_channels().len(), 0);
2422 }
2423
2424 #[test]
2425 fn revoked_output_claim() {
2426         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2427         // transaction is broadcast by its counterparty
2428         let chanmon_cfgs = create_chanmon_cfgs(2);
2429         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2430         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2431         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2432         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2433         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2434         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2435         assert_eq!(revoked_local_txn.len(), 1);
2436         // Only output is the full channel value back to nodes[0]:
2437         assert_eq!(revoked_local_txn[0].output.len(), 1);
2438         // Send a payment through, updating everyone's latest commitment txn
2439         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2440
2441         // Inform nodes[1] that nodes[0] broadcast a stale tx
2442         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2443         check_added_monitors!(nodes[1], 1);
2444         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2445         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2446         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2447
2448         check_spends!(node_txn[0], revoked_local_txn[0]);
2449         check_spends!(node_txn[1], chan_1.3);
2450
2451         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2452         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2453         get_announce_close_broadcast_events(&nodes, 0, 1);
2454         check_added_monitors!(nodes[0], 1);
2455         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2456 }
2457
2458 #[test]
2459 fn claim_htlc_outputs_shared_tx() {
2460         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2461         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2462         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2463         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2464         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2465         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2466
2467         // Create some new channel:
2468         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2469
2470         // Rebalance the network to generate htlc in the two directions
2471         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2472         // 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
2473         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2474         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2475
2476         // Get the will-be-revoked local txn from node[0]
2477         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2478         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2479         assert_eq!(revoked_local_txn[0].input.len(), 1);
2480         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2481         assert_eq!(revoked_local_txn[1].input.len(), 1);
2482         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2483         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2484         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2485
2486         //Revoke the old state
2487         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2488
2489         {
2490                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2491                 check_added_monitors!(nodes[0], 1);
2492                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2493                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2494                 check_added_monitors!(nodes[1], 1);
2495                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2496                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2497                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2498
2499                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2500                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2501
2502                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2503                 check_spends!(node_txn[0], revoked_local_txn[0]);
2504
2505                 let mut witness_lens = BTreeSet::new();
2506                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2507                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2508                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2509                 assert_eq!(witness_lens.len(), 3);
2510                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2511                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2512                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2513
2514                 // Next nodes[1] broadcasts its current local tx state:
2515                 assert_eq!(node_txn[1].input.len(), 1);
2516                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2517         }
2518         get_announce_close_broadcast_events(&nodes, 0, 1);
2519         assert_eq!(nodes[0].node.list_channels().len(), 0);
2520         assert_eq!(nodes[1].node.list_channels().len(), 0);
2521 }
2522
2523 #[test]
2524 fn claim_htlc_outputs_single_tx() {
2525         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2526         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2527         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2528         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2529         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2530         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2531
2532         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2533
2534         // Rebalance the network to generate htlc in the two directions
2535         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2536         // 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
2537         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2538         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2539         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2540
2541         // Get the will-be-revoked local txn from node[0]
2542         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2543
2544         //Revoke the old state
2545         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2546
2547         {
2548                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2549                 check_added_monitors!(nodes[0], 1);
2550                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2551                 check_added_monitors!(nodes[1], 1);
2552                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2553                 let mut events = nodes[0].node.get_and_clear_pending_events();
2554                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2555                 match events[1] {
2556                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2557                         _ => panic!("Unexpected event"),
2558                 }
2559
2560                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2561                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2562
2563                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2564                 assert_eq!(node_txn.len(), 9);
2565                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2566                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2567                 // 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)
2568                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2569
2570                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2571                 assert_eq!(node_txn[0].input.len(), 1);
2572                 check_spends!(node_txn[0], chan_1.3);
2573                 assert_eq!(node_txn[1].input.len(), 1);
2574                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2575                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2576                 check_spends!(node_txn[1], node_txn[0]);
2577
2578                 // Justice transactions are indices 1-2-4
2579                 assert_eq!(node_txn[2].input.len(), 1);
2580                 assert_eq!(node_txn[3].input.len(), 1);
2581                 assert_eq!(node_txn[4].input.len(), 1);
2582
2583                 check_spends!(node_txn[2], revoked_local_txn[0]);
2584                 check_spends!(node_txn[3], revoked_local_txn[0]);
2585                 check_spends!(node_txn[4], revoked_local_txn[0]);
2586
2587                 let mut witness_lens = BTreeSet::new();
2588                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2589                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2590                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2591                 assert_eq!(witness_lens.len(), 3);
2592                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2593                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2594                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2595         }
2596         get_announce_close_broadcast_events(&nodes, 0, 1);
2597         assert_eq!(nodes[0].node.list_channels().len(), 0);
2598         assert_eq!(nodes[1].node.list_channels().len(), 0);
2599 }
2600
2601 #[test]
2602 fn test_htlc_on_chain_success() {
2603         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2604         // the preimage backward accordingly. So here we test that ChannelManager is
2605         // broadcasting the right event to other nodes in payment path.
2606         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2607         // A --------------------> B ----------------------> C (preimage)
2608         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2609         // commitment transaction was broadcast.
2610         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2611         // towards B.
2612         // B should be able to claim via preimage if A then broadcasts its local tx.
2613         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2614         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2615         // PaymentSent event).
2616
2617         let chanmon_cfgs = create_chanmon_cfgs(3);
2618         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2619         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2620         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2621
2622         // Create some initial channels
2623         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2624         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2625
2626         // Ensure all nodes are at the same height
2627         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2628         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2629         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2630         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2631
2632         // Rebalance the network a bit by relaying one payment through all the channels...
2633         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2634         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2635
2636         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2637         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2638
2639         // Broadcast legit commitment tx from C on B's chain
2640         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2641         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2642         assert_eq!(commitment_tx.len(), 1);
2643         check_spends!(commitment_tx[0], chan_2.3);
2644         nodes[2].node.claim_funds(our_payment_preimage);
2645         nodes[2].node.claim_funds(our_payment_preimage_2);
2646         check_added_monitors!(nodes[2], 2);
2647         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2648         assert!(updates.update_add_htlcs.is_empty());
2649         assert!(updates.update_fail_htlcs.is_empty());
2650         assert!(updates.update_fail_malformed_htlcs.is_empty());
2651         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2652
2653         mine_transaction(&nodes[2], &commitment_tx[0]);
2654         check_closed_broadcast!(nodes[2], true);
2655         check_added_monitors!(nodes[2], 1);
2656         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2657         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)
2658         assert_eq!(node_txn.len(), 5);
2659         assert_eq!(node_txn[0], node_txn[3]);
2660         assert_eq!(node_txn[1], node_txn[4]);
2661         assert_eq!(node_txn[2], commitment_tx[0]);
2662         check_spends!(node_txn[0], commitment_tx[0]);
2663         check_spends!(node_txn[1], commitment_tx[0]);
2664         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2665         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2666         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2667         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2668         assert_eq!(node_txn[0].lock_time, 0);
2669         assert_eq!(node_txn[1].lock_time, 0);
2670
2671         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2672         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2673         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2674         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2675         {
2676                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2677                 assert_eq!(added_monitors.len(), 1);
2678                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2679                 added_monitors.clear();
2680         }
2681         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2682         assert_eq!(forwarded_events.len(), 3);
2683         match forwarded_events[0] {
2684                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2685                 _ => panic!("Unexpected event"),
2686         }
2687         let chan_id = Some(chan_1.2);
2688         match forwarded_events[1] {
2689                 Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
2690                         assert_eq!(fee_earned_msat, Some(1000));
2691                         assert_eq!(source_channel_id, chan_id);
2692                         assert_eq!(claim_from_onchain_tx, true);
2693                 },
2694                 _ => panic!()
2695         }
2696         match forwarded_events[2] {
2697                 Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
2698                         assert_eq!(fee_earned_msat, Some(1000));
2699                         assert_eq!(source_channel_id, chan_id);
2700                         assert_eq!(claim_from_onchain_tx, true);
2701                 },
2702                 _ => panic!()
2703         }
2704         let events = nodes[1].node.get_and_clear_pending_msg_events();
2705         {
2706                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2707                 assert_eq!(added_monitors.len(), 2);
2708                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2709                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2710                 added_monitors.clear();
2711         }
2712         assert_eq!(events.len(), 3);
2713         match events[0] {
2714                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2715                 _ => panic!("Unexpected event"),
2716         }
2717         match events[1] {
2718                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2719                 _ => panic!("Unexpected event"),
2720         }
2721
2722         match events[2] {
2723                 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, .. } } => {
2724                         assert!(update_add_htlcs.is_empty());
2725                         assert!(update_fail_htlcs.is_empty());
2726                         assert_eq!(update_fulfill_htlcs.len(), 1);
2727                         assert!(update_fail_malformed_htlcs.is_empty());
2728                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2729                 },
2730                 _ => panic!("Unexpected event"),
2731         };
2732         macro_rules! check_tx_local_broadcast {
2733                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2734                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2735                         assert_eq!(node_txn.len(), 3);
2736                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2737                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2738                         check_spends!(node_txn[1], $commitment_tx);
2739                         check_spends!(node_txn[2], $commitment_tx);
2740                         assert_ne!(node_txn[1].lock_time, 0);
2741                         assert_ne!(node_txn[2].lock_time, 0);
2742                         if $htlc_offered {
2743                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2744                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2745                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2746                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2747                         } else {
2748                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2749                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2750                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2751                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2752                         }
2753                         check_spends!(node_txn[0], $chan_tx);
2754                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2755                         node_txn.clear();
2756                 } }
2757         }
2758         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2759         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2760         // timeout-claim of the output that nodes[2] just claimed via success.
2761         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2762
2763         // Broadcast legit commitment tx from A on B's chain
2764         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2765         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2766         check_spends!(node_a_commitment_tx[0], chan_1.3);
2767         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2768         check_closed_broadcast!(nodes[1], true);
2769         check_added_monitors!(nodes[1], 1);
2770         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2771         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2772         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2773         let commitment_spend =
2774                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2775                         check_spends!(node_txn[1], commitment_tx[0]);
2776                         check_spends!(node_txn[2], commitment_tx[0]);
2777                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2778                         &node_txn[0]
2779                 } else {
2780                         check_spends!(node_txn[0], commitment_tx[0]);
2781                         check_spends!(node_txn[1], commitment_tx[0]);
2782                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2783                         &node_txn[2]
2784                 };
2785
2786         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2787         assert_eq!(commitment_spend.input.len(), 2);
2788         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2789         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2790         assert_eq!(commitment_spend.lock_time, 0);
2791         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2792         check_spends!(node_txn[3], chan_1.3);
2793         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2794         check_spends!(node_txn[4], node_txn[3]);
2795         check_spends!(node_txn[5], node_txn[3]);
2796         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2797         // we already checked the same situation with A.
2798
2799         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2800         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2801         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2802         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2803         check_closed_broadcast!(nodes[0], true);
2804         check_added_monitors!(nodes[0], 1);
2805         let events = nodes[0].node.get_and_clear_pending_events();
2806         assert_eq!(events.len(), 5);
2807         let mut first_claimed = false;
2808         for event in events {
2809                 match event {
2810                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2811                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2812                                         assert!(!first_claimed);
2813                                         first_claimed = true;
2814                                 } else {
2815                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2816                                         assert_eq!(payment_hash, payment_hash_2);
2817                                 }
2818                         },
2819                         Event::PaymentPathSuccessful { .. } => {},
2820                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2821                         _ => panic!("Unexpected event"),
2822                 }
2823         }
2824         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2825 }
2826
2827 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2828         // Test that in case of a unilateral close onchain, we detect the state of output and
2829         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2830         // broadcasting the right event to other nodes in payment path.
2831         // A ------------------> B ----------------------> C (timeout)
2832         //    B's commitment tx                 C's commitment tx
2833         //            \                                  \
2834         //         B's HTLC timeout tx               B's timeout tx
2835
2836         let chanmon_cfgs = create_chanmon_cfgs(3);
2837         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2838         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2839         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2840         *nodes[0].connect_style.borrow_mut() = connect_style;
2841         *nodes[1].connect_style.borrow_mut() = connect_style;
2842         *nodes[2].connect_style.borrow_mut() = connect_style;
2843
2844         // Create some intial channels
2845         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2846         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2847
2848         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2849         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2850         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2851
2852         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2853
2854         // Broadcast legit commitment tx from C on B's chain
2855         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2856         check_spends!(commitment_tx[0], chan_2.3);
2857         nodes[2].node.fail_htlc_backwards(&payment_hash);
2858         check_added_monitors!(nodes[2], 0);
2859         expect_pending_htlcs_forwardable!(nodes[2]);
2860         check_added_monitors!(nodes[2], 1);
2861
2862         let events = nodes[2].node.get_and_clear_pending_msg_events();
2863         assert_eq!(events.len(), 1);
2864         match events[0] {
2865                 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, .. } } => {
2866                         assert!(update_add_htlcs.is_empty());
2867                         assert!(!update_fail_htlcs.is_empty());
2868                         assert!(update_fulfill_htlcs.is_empty());
2869                         assert!(update_fail_malformed_htlcs.is_empty());
2870                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2871                 },
2872                 _ => panic!("Unexpected event"),
2873         };
2874         mine_transaction(&nodes[2], &commitment_tx[0]);
2875         check_closed_broadcast!(nodes[2], true);
2876         check_added_monitors!(nodes[2], 1);
2877         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2878         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2879         assert_eq!(node_txn.len(), 1);
2880         check_spends!(node_txn[0], chan_2.3);
2881         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2882
2883         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2884         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2885         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2886         mine_transaction(&nodes[1], &commitment_tx[0]);
2887         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2888         let timeout_tx;
2889         {
2890                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2891                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2892                 assert_eq!(node_txn[0], node_txn[3]);
2893                 assert_eq!(node_txn[1], node_txn[4]);
2894
2895                 check_spends!(node_txn[2], commitment_tx[0]);
2896                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2897
2898                 check_spends!(node_txn[0], chan_2.3);
2899                 check_spends!(node_txn[1], node_txn[0]);
2900                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2901                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2902
2903                 timeout_tx = node_txn[2].clone();
2904                 node_txn.clear();
2905         }
2906
2907         mine_transaction(&nodes[1], &timeout_tx);
2908         check_added_monitors!(nodes[1], 1);
2909         check_closed_broadcast!(nodes[1], true);
2910         {
2911                 // B will rebroadcast a fee-bumped timeout transaction here.
2912                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2913                 assert_eq!(node_txn.len(), 1);
2914                 check_spends!(node_txn[0], commitment_tx[0]);
2915         }
2916
2917         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2918         {
2919                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2920                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2921                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2922                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2923                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2924                 if node_txn.len() == 1 {
2925                         check_spends!(node_txn[0], chan_2.3);
2926                 } else {
2927                         assert_eq!(node_txn.len(), 0);
2928                 }
2929         }
2930
2931         expect_pending_htlcs_forwardable!(nodes[1]);
2932         check_added_monitors!(nodes[1], 1);
2933         let events = nodes[1].node.get_and_clear_pending_msg_events();
2934         assert_eq!(events.len(), 1);
2935         match events[0] {
2936                 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, .. } } => {
2937                         assert!(update_add_htlcs.is_empty());
2938                         assert!(!update_fail_htlcs.is_empty());
2939                         assert!(update_fulfill_htlcs.is_empty());
2940                         assert!(update_fail_malformed_htlcs.is_empty());
2941                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2942                 },
2943                 _ => panic!("Unexpected event"),
2944         };
2945
2946         // Broadcast legit commitment tx from B on A's chain
2947         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2948         check_spends!(commitment_tx[0], chan_1.3);
2949
2950         mine_transaction(&nodes[0], &commitment_tx[0]);
2951         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2952
2953         check_closed_broadcast!(nodes[0], true);
2954         check_added_monitors!(nodes[0], 1);
2955         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2956         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2957         assert_eq!(node_txn.len(), 2);
2958         check_spends!(node_txn[0], chan_1.3);
2959         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2960         check_spends!(node_txn[1], commitment_tx[0]);
2961         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2962 }
2963
2964 #[test]
2965 fn test_htlc_on_chain_timeout() {
2966         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2967         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2968         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2969 }
2970
2971 #[test]
2972 fn test_simple_commitment_revoked_fail_backward() {
2973         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2974         // and fail backward accordingly.
2975
2976         let chanmon_cfgs = create_chanmon_cfgs(3);
2977         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2978         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2979         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2980
2981         // Create some initial channels
2982         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2983         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2984
2985         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2986         // Get the will-be-revoked local txn from nodes[2]
2987         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2988         // Revoke the old state
2989         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2990
2991         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2992
2993         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2994         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2995         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2996         check_added_monitors!(nodes[1], 1);
2997         check_closed_broadcast!(nodes[1], true);
2998
2999         expect_pending_htlcs_forwardable!(nodes[1]);
3000         check_added_monitors!(nodes[1], 1);
3001         let events = nodes[1].node.get_and_clear_pending_msg_events();
3002         assert_eq!(events.len(), 1);
3003         match events[0] {
3004                 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, .. } } => {
3005                         assert!(update_add_htlcs.is_empty());
3006                         assert_eq!(update_fail_htlcs.len(), 1);
3007                         assert!(update_fulfill_htlcs.is_empty());
3008                         assert!(update_fail_malformed_htlcs.is_empty());
3009                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3010
3011                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3012                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3013                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3014                 },
3015                 _ => panic!("Unexpected event"),
3016         }
3017 }
3018
3019 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3020         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3021         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3022         // commitment transaction anymore.
3023         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3024         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3025         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3026         // technically disallowed and we should probably handle it reasonably.
3027         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3028         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3029         // transactions:
3030         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3031         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3032         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3033         //   and once they revoke the previous commitment transaction (allowing us to send a new
3034         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3035         let chanmon_cfgs = create_chanmon_cfgs(3);
3036         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3037         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3038         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3039
3040         // Create some initial channels
3041         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3042         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3043
3044         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 });
3045         // Get the will-be-revoked local txn from nodes[2]
3046         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3047         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3048         // Revoke the old state
3049         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3050
3051         let value = if use_dust {
3052                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3053                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3054                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3055         } else { 3000000 };
3056
3057         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3058         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3059         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3060
3061         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
3062         expect_pending_htlcs_forwardable!(nodes[2]);
3063         check_added_monitors!(nodes[2], 1);
3064         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3065         assert!(updates.update_add_htlcs.is_empty());
3066         assert!(updates.update_fulfill_htlcs.is_empty());
3067         assert!(updates.update_fail_malformed_htlcs.is_empty());
3068         assert_eq!(updates.update_fail_htlcs.len(), 1);
3069         assert!(updates.update_fee.is_none());
3070         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3071         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3072         // Drop the last RAA from 3 -> 2
3073
3074         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
3075         expect_pending_htlcs_forwardable!(nodes[2]);
3076         check_added_monitors!(nodes[2], 1);
3077         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3078         assert!(updates.update_add_htlcs.is_empty());
3079         assert!(updates.update_fulfill_htlcs.is_empty());
3080         assert!(updates.update_fail_malformed_htlcs.is_empty());
3081         assert_eq!(updates.update_fail_htlcs.len(), 1);
3082         assert!(updates.update_fee.is_none());
3083         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3084         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3085         check_added_monitors!(nodes[1], 1);
3086         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3087         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3088         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3089         check_added_monitors!(nodes[2], 1);
3090
3091         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3092         expect_pending_htlcs_forwardable!(nodes[2]);
3093         check_added_monitors!(nodes[2], 1);
3094         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3095         assert!(updates.update_add_htlcs.is_empty());
3096         assert!(updates.update_fulfill_htlcs.is_empty());
3097         assert!(updates.update_fail_malformed_htlcs.is_empty());
3098         assert_eq!(updates.update_fail_htlcs.len(), 1);
3099         assert!(updates.update_fee.is_none());
3100         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3101         // At this point first_payment_hash has dropped out of the latest two commitment
3102         // transactions that nodes[1] is tracking...
3103         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3104         check_added_monitors!(nodes[1], 1);
3105         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3106         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3107         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3108         check_added_monitors!(nodes[2], 1);
3109
3110         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3111         // on nodes[2]'s RAA.
3112         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3113         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3114         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3115         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3116         check_added_monitors!(nodes[1], 0);
3117
3118         if deliver_bs_raa {
3119                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3120                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3121                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3122                 check_added_monitors!(nodes[1], 1);
3123                 let events = nodes[1].node.get_and_clear_pending_events();
3124                 assert_eq!(events.len(), 1);
3125                 match events[0] {
3126                         Event::PendingHTLCsForwardable { .. } => { },
3127                         _ => panic!("Unexpected event"),
3128                 };
3129                 // Deliberately don't process the pending fail-back so they all fail back at once after
3130                 // block connection just like the !deliver_bs_raa case
3131         }
3132
3133         let mut failed_htlcs = HashSet::new();
3134         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3135
3136         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3137         check_added_monitors!(nodes[1], 1);
3138         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3139         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3140
3141         let events = nodes[1].node.get_and_clear_pending_events();
3142         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3143         match events[0] {
3144                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3145                 _ => panic!("Unexepected event"),
3146         }
3147         match events[1] {
3148                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3149                         assert_eq!(*payment_hash, fourth_payment_hash);
3150                 },
3151                 _ => panic!("Unexpected event"),
3152         }
3153         if !deliver_bs_raa {
3154                 match events[2] {
3155                         Event::PaymentFailed { ref payment_hash, .. } => {
3156                                 assert_eq!(*payment_hash, fourth_payment_hash);
3157                         },
3158                         _ => panic!("Unexpected event"),
3159                 }
3160                 match events[3] {
3161                         Event::PendingHTLCsForwardable { .. } => { },
3162                         _ => panic!("Unexpected event"),
3163                 };
3164         }
3165         nodes[1].node.process_pending_htlc_forwards();
3166         check_added_monitors!(nodes[1], 1);
3167
3168         let events = nodes[1].node.get_and_clear_pending_msg_events();
3169         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3170         match events[if deliver_bs_raa { 1 } else { 0 }] {
3171                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3172                 _ => panic!("Unexpected event"),
3173         }
3174         match events[if deliver_bs_raa { 2 } else { 1 }] {
3175                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3176                         assert_eq!(channel_id, chan_2.2);
3177                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3178                 },
3179                 _ => panic!("Unexpected event"),
3180         }
3181         if deliver_bs_raa {
3182                 match events[0] {
3183                         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, .. } } => {
3184                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3185                                 assert_eq!(update_add_htlcs.len(), 1);
3186                                 assert!(update_fulfill_htlcs.is_empty());
3187                                 assert!(update_fail_htlcs.is_empty());
3188                                 assert!(update_fail_malformed_htlcs.is_empty());
3189                         },
3190                         _ => panic!("Unexpected event"),
3191                 }
3192         }
3193         match events[if deliver_bs_raa { 3 } else { 2 }] {
3194                 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, .. } } => {
3195                         assert!(update_add_htlcs.is_empty());
3196                         assert_eq!(update_fail_htlcs.len(), 3);
3197                         assert!(update_fulfill_htlcs.is_empty());
3198                         assert!(update_fail_malformed_htlcs.is_empty());
3199                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3200
3201                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3202                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3203                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3204
3205                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3206
3207                         let events = nodes[0].node.get_and_clear_pending_events();
3208                         assert_eq!(events.len(), 3);
3209                         match events[0] {
3210                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3211                                         assert!(failed_htlcs.insert(payment_hash.0));
3212                                         // If we delivered B's RAA we got an unknown preimage error, not something
3213                                         // that we should update our routing table for.
3214                                         if !deliver_bs_raa {
3215                                                 assert!(network_update.is_some());
3216                                         }
3217                                 },
3218                                 _ => panic!("Unexpected event"),
3219                         }
3220                         match events[1] {
3221                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3222                                         assert!(failed_htlcs.insert(payment_hash.0));
3223                                         assert!(network_update.is_some());
3224                                 },
3225                                 _ => panic!("Unexpected event"),
3226                         }
3227                         match events[2] {
3228                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3229                                         assert!(failed_htlcs.insert(payment_hash.0));
3230                                         assert!(network_update.is_some());
3231                                 },
3232                                 _ => panic!("Unexpected event"),
3233                         }
3234                 },
3235                 _ => panic!("Unexpected event"),
3236         }
3237
3238         assert!(failed_htlcs.contains(&first_payment_hash.0));
3239         assert!(failed_htlcs.contains(&second_payment_hash.0));
3240         assert!(failed_htlcs.contains(&third_payment_hash.0));
3241 }
3242
3243 #[test]
3244 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3245         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3246         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3247         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3248         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3249 }
3250
3251 #[test]
3252 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3253         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3254         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3255         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3256         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3257 }
3258
3259 #[test]
3260 fn fail_backward_pending_htlc_upon_channel_failure() {
3261         let chanmon_cfgs = create_chanmon_cfgs(2);
3262         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3263         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3264         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3265         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3266
3267         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3268         {
3269                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3270                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3271                 check_added_monitors!(nodes[0], 1);
3272
3273                 let payment_event = {
3274                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3275                         assert_eq!(events.len(), 1);
3276                         SendEvent::from_event(events.remove(0))
3277                 };
3278                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3279                 assert_eq!(payment_event.msgs.len(), 1);
3280         }
3281
3282         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3283         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3284         {
3285                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3286                 check_added_monitors!(nodes[0], 0);
3287
3288                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3289         }
3290
3291         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3292         {
3293                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3294
3295                 let secp_ctx = Secp256k1::new();
3296                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3297                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3298                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3299                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3300                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3301
3302                 // Send a 0-msat update_add_htlc to fail the channel.
3303                 let update_add_htlc = msgs::UpdateAddHTLC {
3304                         channel_id: chan.2,
3305                         htlc_id: 0,
3306                         amount_msat: 0,
3307                         payment_hash,
3308                         cltv_expiry,
3309                         onion_routing_packet,
3310                 };
3311                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3312         }
3313         let events = nodes[0].node.get_and_clear_pending_events();
3314         assert_eq!(events.len(), 2);
3315         // Check that Alice fails backward the pending HTLC from the second payment.
3316         match events[0] {
3317                 Event::PaymentPathFailed { payment_hash, .. } => {
3318                         assert_eq!(payment_hash, failed_payment_hash);
3319                 },
3320                 _ => panic!("Unexpected event"),
3321         }
3322         match events[1] {
3323                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3324                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3325                 },
3326                 _ => panic!("Unexpected event {:?}", events[1]),
3327         }
3328         check_closed_broadcast!(nodes[0], true);
3329         check_added_monitors!(nodes[0], 1);
3330 }
3331
3332 #[test]
3333 fn test_htlc_ignore_latest_remote_commitment() {
3334         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3335         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3336         let chanmon_cfgs = create_chanmon_cfgs(2);
3337         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3338         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3339         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3340         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3341
3342         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3343         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3344         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3345         check_closed_broadcast!(nodes[0], true);
3346         check_added_monitors!(nodes[0], 1);
3347         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3348
3349         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3350         assert_eq!(node_txn.len(), 3);
3351         assert_eq!(node_txn[0], node_txn[1]);
3352
3353         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3354         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3355         check_closed_broadcast!(nodes[1], true);
3356         check_added_monitors!(nodes[1], 1);
3357         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3358
3359         // Duplicate the connect_block call since this may happen due to other listeners
3360         // registering new transactions
3361         header.prev_blockhash = header.block_hash();
3362         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3363 }
3364
3365 #[test]
3366 fn test_force_close_fail_back() {
3367         // Check which HTLCs are failed-backwards on channel force-closure
3368         let chanmon_cfgs = create_chanmon_cfgs(3);
3369         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3370         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3371         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3372         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3373         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3374
3375         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3376
3377         let mut payment_event = {
3378                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3379                 check_added_monitors!(nodes[0], 1);
3380
3381                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3382                 assert_eq!(events.len(), 1);
3383                 SendEvent::from_event(events.remove(0))
3384         };
3385
3386         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3387         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3388
3389         expect_pending_htlcs_forwardable!(nodes[1]);
3390
3391         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3392         assert_eq!(events_2.len(), 1);
3393         payment_event = SendEvent::from_event(events_2.remove(0));
3394         assert_eq!(payment_event.msgs.len(), 1);
3395
3396         check_added_monitors!(nodes[1], 1);
3397         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3398         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3399         check_added_monitors!(nodes[2], 1);
3400         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3401
3402         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3403         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3404         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3405
3406         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3407         check_closed_broadcast!(nodes[2], true);
3408         check_added_monitors!(nodes[2], 1);
3409         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3410         let tx = {
3411                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3412                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3413                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3414                 // back to nodes[1] upon timeout otherwise.
3415                 assert_eq!(node_txn.len(), 1);
3416                 node_txn.remove(0)
3417         };
3418
3419         mine_transaction(&nodes[1], &tx);
3420
3421         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3422         check_closed_broadcast!(nodes[1], true);
3423         check_added_monitors!(nodes[1], 1);
3424         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3425
3426         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3427         {
3428                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3429                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3430         }
3431         mine_transaction(&nodes[2], &tx);
3432         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3433         assert_eq!(node_txn.len(), 1);
3434         assert_eq!(node_txn[0].input.len(), 1);
3435         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3436         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3437         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3438
3439         check_spends!(node_txn[0], tx);
3440 }
3441
3442 #[test]
3443 fn test_dup_events_on_peer_disconnect() {
3444         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3445         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3446         // as we used to generate the event immediately upon receipt of the payment preimage in the
3447         // update_fulfill_htlc message.
3448
3449         let chanmon_cfgs = create_chanmon_cfgs(2);
3450         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3451         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3452         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3453         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3454
3455         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3456
3457         assert!(nodes[1].node.claim_funds(payment_preimage));
3458         check_added_monitors!(nodes[1], 1);
3459         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3460         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3461         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3462
3463         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3464         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3465
3466         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3467         expect_payment_path_successful!(nodes[0]);
3468 }
3469
3470 #[test]
3471 fn test_simple_peer_disconnect() {
3472         // Test that we can reconnect when there are no lost messages
3473         let chanmon_cfgs = create_chanmon_cfgs(3);
3474         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3475         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3476         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3477         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3478         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3479
3480         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3481         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3482         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3483
3484         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3485         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3486         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3487         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3488
3489         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3490         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3491         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3492
3493         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3494         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3495         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3496         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3497
3498         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3499         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3500
3501         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3502         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3503
3504         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3505         {
3506                 let events = nodes[0].node.get_and_clear_pending_events();
3507                 assert_eq!(events.len(), 3);
3508                 match events[0] {
3509                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3510                                 assert_eq!(payment_preimage, payment_preimage_3);
3511                                 assert_eq!(payment_hash, payment_hash_3);
3512                         },
3513                         _ => panic!("Unexpected event"),
3514                 }
3515                 match events[1] {
3516                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3517                                 assert_eq!(payment_hash, payment_hash_5);
3518                                 assert!(rejected_by_dest);
3519                         },
3520                         _ => panic!("Unexpected event"),
3521                 }
3522                 match events[2] {
3523                         Event::PaymentPathSuccessful { .. } => {},
3524                         _ => panic!("Unexpected event"),
3525                 }
3526         }
3527
3528         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3529         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3530 }
3531
3532 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3533         // Test that we can reconnect when in-flight HTLC updates get dropped
3534         let chanmon_cfgs = create_chanmon_cfgs(2);
3535         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3536         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3537         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3538
3539         let mut as_funding_locked = None;
3540         if messages_delivered == 0 {
3541                 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3542                 as_funding_locked = Some(funding_locked);
3543                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3544                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3545                 // it before the channel_reestablish message.
3546         } else {
3547                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3548         }
3549
3550         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3551
3552         let payment_event = {
3553                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3554                 check_added_monitors!(nodes[0], 1);
3555
3556                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3557                 assert_eq!(events.len(), 1);
3558                 SendEvent::from_event(events.remove(0))
3559         };
3560         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3561
3562         if messages_delivered < 2 {
3563                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3564         } else {
3565                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3566                 if messages_delivered >= 3 {
3567                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3568                         check_added_monitors!(nodes[1], 1);
3569                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3570
3571                         if messages_delivered >= 4 {
3572                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3573                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3574                                 check_added_monitors!(nodes[0], 1);
3575
3576                                 if messages_delivered >= 5 {
3577                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3578                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3579                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3580                                         check_added_monitors!(nodes[0], 1);
3581
3582                                         if messages_delivered >= 6 {
3583                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3584                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3585                                                 check_added_monitors!(nodes[1], 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 < 3 {
3595                 if simulate_broken_lnd {
3596                         // lnd has a long-standing bug where they send a funding_locked prior to a
3597                         // channel_reestablish if you reconnect prior to funding_locked time.
3598                         //
3599                         // Here we simulate that behavior, delivering a funding_locked immediately on
3600                         // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3601                         // in `reconnect_nodes` but we currently don't fail based on that.
3602                         //
3603                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3604                         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3605                 }
3606                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3607                 // received on either side, both sides will need to resend them.
3608                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3609         } else if messages_delivered == 3 {
3610                 // nodes[0] still wants its RAA + commitment_signed
3611                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3612         } else if messages_delivered == 4 {
3613                 // nodes[0] still wants its commitment_signed
3614                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3615         } else if messages_delivered == 5 {
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), (false, true));
3618         } else if messages_delivered == 6 {
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         let events_1 = nodes[1].node.get_and_clear_pending_events();
3624         assert_eq!(events_1.len(), 1);
3625         match events_1[0] {
3626                 Event::PendingHTLCsForwardable { .. } => { },
3627                 _ => panic!("Unexpected event"),
3628         };
3629
3630         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3631         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3632         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3633
3634         nodes[1].node.process_pending_htlc_forwards();
3635
3636         let events_2 = nodes[1].node.get_and_clear_pending_events();
3637         assert_eq!(events_2.len(), 1);
3638         match events_2[0] {
3639                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3640                         assert_eq!(payment_hash_1, *payment_hash);
3641                         assert_eq!(amt, 1000000);
3642                         match &purpose {
3643                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3644                                         assert!(payment_preimage.is_none());
3645                                         assert_eq!(payment_secret_1, *payment_secret);
3646                                 },
3647                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3648                         }
3649                 },
3650                 _ => panic!("Unexpected event"),
3651         }
3652
3653         nodes[1].node.claim_funds(payment_preimage_1);
3654         check_added_monitors!(nodes[1], 1);
3655
3656         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3657         assert_eq!(events_3.len(), 1);
3658         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3659                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3660                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3661                         assert!(updates.update_add_htlcs.is_empty());
3662                         assert!(updates.update_fail_htlcs.is_empty());
3663                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3664                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3665                         assert!(updates.update_fee.is_none());
3666                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3667                 },
3668                 _ => panic!("Unexpected event"),
3669         };
3670
3671         if messages_delivered >= 1 {
3672                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3673
3674                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3675                 assert_eq!(events_4.len(), 1);
3676                 match events_4[0] {
3677                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3678                                 assert_eq!(payment_preimage_1, *payment_preimage);
3679                                 assert_eq!(payment_hash_1, *payment_hash);
3680                         },
3681                         _ => panic!("Unexpected event"),
3682                 }
3683
3684                 if messages_delivered >= 2 {
3685                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3686                         check_added_monitors!(nodes[0], 1);
3687                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3688
3689                         if messages_delivered >= 3 {
3690                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3691                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3692                                 check_added_monitors!(nodes[1], 1);
3693
3694                                 if messages_delivered >= 4 {
3695                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3696                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3697                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3698                                         check_added_monitors!(nodes[1], 1);
3699
3700                                         if messages_delivered >= 5 {
3701                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3702                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3703                                                 check_added_monitors!(nodes[0], 1);
3704                                         }
3705                                 }
3706                         }
3707                 }
3708         }
3709
3710         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3711         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3712         if messages_delivered < 2 {
3713                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3714                 if messages_delivered < 1 {
3715                         expect_payment_sent!(nodes[0], payment_preimage_1);
3716                 } else {
3717                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3718                 }
3719         } else if messages_delivered == 2 {
3720                 // nodes[0] still wants its RAA + commitment_signed
3721                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3722         } else if messages_delivered == 3 {
3723                 // nodes[0] still wants its commitment_signed
3724                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3725         } else if messages_delivered == 4 {
3726                 // nodes[1] still wants its final RAA
3727                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3728         } else if messages_delivered == 5 {
3729                 // Everything was delivered...
3730                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3731         }
3732
3733         if messages_delivered == 1 || messages_delivered == 2 {
3734                 expect_payment_path_successful!(nodes[0]);
3735         }
3736
3737         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3738         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3739         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3740
3741         if messages_delivered > 2 {
3742                 expect_payment_path_successful!(nodes[0]);
3743         }
3744
3745         // Channel should still work fine...
3746         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3747         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3748         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3749 }
3750
3751 #[test]
3752 fn test_drop_messages_peer_disconnect_a() {
3753         do_test_drop_messages_peer_disconnect(0, true);
3754         do_test_drop_messages_peer_disconnect(0, false);
3755         do_test_drop_messages_peer_disconnect(1, false);
3756         do_test_drop_messages_peer_disconnect(2, false);
3757 }
3758
3759 #[test]
3760 fn test_drop_messages_peer_disconnect_b() {
3761         do_test_drop_messages_peer_disconnect(3, false);
3762         do_test_drop_messages_peer_disconnect(4, false);
3763         do_test_drop_messages_peer_disconnect(5, false);
3764         do_test_drop_messages_peer_disconnect(6, false);
3765 }
3766
3767 #[test]
3768 fn test_funding_peer_disconnect() {
3769         // Test that we can lock in our funding tx while disconnected
3770         let chanmon_cfgs = create_chanmon_cfgs(2);
3771         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3772         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3773         let persister: test_utils::TestPersister;
3774         let new_chain_monitor: test_utils::TestChainMonitor;
3775         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3776         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3777         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3778
3779         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3780         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3781
3782         confirm_transaction(&nodes[0], &tx);
3783         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3784         assert!(events_1.is_empty());
3785
3786         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3787
3788         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3789         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3790
3791         confirm_transaction(&nodes[1], &tx);
3792         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3793         assert!(events_2.is_empty());
3794
3795         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3796         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3797         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3798         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3799
3800         // nodes[0] hasn't yet received a funding_locked, so it only sends that on reconnect.
3801         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3802         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3803         assert_eq!(events_3.len(), 1);
3804         let as_funding_locked = match events_3[0] {
3805                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3806                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3807                         msg.clone()
3808                 },
3809                 _ => panic!("Unexpected event {:?}", events_3[0]),
3810         };
3811
3812         // nodes[1] received nodes[0]'s funding_locked on the first reconnect above, so it should send
3813         // announcement_signatures as well as channel_update.
3814         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3815         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3816         assert_eq!(events_4.len(), 3);
3817         let chan_id;
3818         let bs_funding_locked = match events_4[0] {
3819                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3820                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3821                         chan_id = msg.channel_id;
3822                         msg.clone()
3823                 },
3824                 _ => panic!("Unexpected event {:?}", events_4[0]),
3825         };
3826         let bs_announcement_sigs = match events_4[1] {
3827                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3828                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3829                         msg.clone()
3830                 },
3831                 _ => panic!("Unexpected event {:?}", events_4[1]),
3832         };
3833         match events_4[2] {
3834                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3835                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3836                 },
3837                 _ => panic!("Unexpected event {:?}", events_4[2]),
3838         }
3839
3840         // Re-deliver nodes[0]'s funding_locked, which nodes[1] can safely ignore. It currently
3841         // generates a duplicative private channel_update
3842         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
3843         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3844         assert_eq!(events_5.len(), 1);
3845         match events_5[0] {
3846                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3847                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3848                 },
3849                 _ => panic!("Unexpected event {:?}", events_5[0]),
3850         };
3851
3852         // When we deliver nodes[1]'s funding_locked, however, nodes[0] will generate its
3853         // announcement_signatures.
3854         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding_locked);
3855         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3856         assert_eq!(events_6.len(), 1);
3857         let as_announcement_sigs = match events_6[0] {
3858                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3859                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3860                         msg.clone()
3861                 },
3862                 _ => panic!("Unexpected event {:?}", events_6[0]),
3863         };
3864
3865         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3866         // broadcast the channel announcement globally, as well as re-send its (now-public)
3867         // channel_update.
3868         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3869         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3870         assert_eq!(events_7.len(), 1);
3871         let (chan_announcement, as_update) = match events_7[0] {
3872                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3873                         (msg.clone(), update_msg.clone())
3874                 },
3875                 _ => panic!("Unexpected event {:?}", events_7[0]),
3876         };
3877
3878         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3879         // same channel_announcement.
3880         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3881         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3882         assert_eq!(events_8.len(), 1);
3883         let bs_update = match events_8[0] {
3884                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3885                         assert_eq!(*msg, chan_announcement);
3886                         update_msg.clone()
3887                 },
3888                 _ => panic!("Unexpected event {:?}", events_8[0]),
3889         };
3890
3891         // Provide the channel announcement and public updates to the network graph
3892         nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap();
3893         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3894         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3895
3896         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3897         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3898         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3899
3900         // Check that after deserialization and reconnection we can still generate an identical
3901         // channel_announcement from the cached signatures.
3902         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3903
3904         let nodes_0_serialized = nodes[0].node.encode();
3905         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3906         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3907
3908         persister = test_utils::TestPersister::new();
3909         let keys_manager = &chanmon_cfgs[0].keys_manager;
3910         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);
3911         nodes[0].chain_monitor = &new_chain_monitor;
3912         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3913         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3914                 &mut chan_0_monitor_read, keys_manager).unwrap();
3915         assert!(chan_0_monitor_read.is_empty());
3916
3917         let mut nodes_0_read = &nodes_0_serialized[..];
3918         let (_, nodes_0_deserialized_tmp) = {
3919                 let mut channel_monitors = HashMap::new();
3920                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3921                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3922                         default_config: UserConfig::default(),
3923                         keys_manager,
3924                         fee_estimator: node_cfgs[0].fee_estimator,
3925                         chain_monitor: nodes[0].chain_monitor,
3926                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3927                         logger: nodes[0].logger,
3928                         channel_monitors,
3929                 }).unwrap()
3930         };
3931         nodes_0_deserialized = nodes_0_deserialized_tmp;
3932         assert!(nodes_0_read.is_empty());
3933
3934         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3935         nodes[0].node = &nodes_0_deserialized;
3936         check_added_monitors!(nodes[0], 1);
3937
3938         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3939
3940         // The channel announcement should be re-generated exactly by broadcast_node_announcement.
3941         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3942         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3943         let mut found_announcement = false;
3944         for event in msgs.iter() {
3945                 match event {
3946                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3947                                 if *msg == chan_announcement { found_announcement = true; }
3948                         },
3949                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3950                         _ => panic!("Unexpected event"),
3951                 }
3952         }
3953         assert!(found_announcement);
3954 }
3955
3956 #[test]
3957 fn test_funding_locked_without_best_block_updated() {
3958         // Previously, if we were offline when a funding transaction was locked in, and then we came
3959         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3960         // generate a funding_locked until a later best_block_updated. This tests that we generate the
3961         // funding_locked immediately instead.
3962         let chanmon_cfgs = create_chanmon_cfgs(2);
3963         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3964         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3965         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3966         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3967
3968         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
3969
3970         let conf_height = nodes[0].best_block_info().1 + 1;
3971         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3972         let block_txn = [funding_tx];
3973         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3974         let conf_block_header = nodes[0].get_block_header(conf_height);
3975         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3976
3977         // Ensure nodes[0] generates a funding_locked after the transactions_confirmed
3978         let as_funding_locked = get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id());
3979         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
3980 }
3981
3982 #[test]
3983 fn test_drop_messages_peer_disconnect_dual_htlc() {
3984         // Test that we can handle reconnecting when both sides of a channel have pending
3985         // commitment_updates when we disconnect.
3986         let chanmon_cfgs = create_chanmon_cfgs(2);
3987         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3988         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3989         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3990         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3991
3992         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3993
3994         // Now try to send a second payment which will fail to send
3995         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3996         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3997         check_added_monitors!(nodes[0], 1);
3998
3999         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4000         assert_eq!(events_1.len(), 1);
4001         match events_1[0] {
4002                 MessageSendEvent::UpdateHTLCs { .. } => {},
4003                 _ => panic!("Unexpected event"),
4004         }
4005
4006         assert!(nodes[1].node.claim_funds(payment_preimage_1));
4007         check_added_monitors!(nodes[1], 1);
4008
4009         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4010         assert_eq!(events_2.len(), 1);
4011         match events_2[0] {
4012                 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 } } => {
4013                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4014                         assert!(update_add_htlcs.is_empty());
4015                         assert_eq!(update_fulfill_htlcs.len(), 1);
4016                         assert!(update_fail_htlcs.is_empty());
4017                         assert!(update_fail_malformed_htlcs.is_empty());
4018                         assert!(update_fee.is_none());
4019
4020                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4021                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4022                         assert_eq!(events_3.len(), 1);
4023                         match events_3[0] {
4024                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4025                                         assert_eq!(*payment_preimage, payment_preimage_1);
4026                                         assert_eq!(*payment_hash, payment_hash_1);
4027                                 },
4028                                 _ => panic!("Unexpected event"),
4029                         }
4030
4031                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4032                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4033                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4034                         check_added_monitors!(nodes[0], 1);
4035                 },
4036                 _ => panic!("Unexpected event"),
4037         }
4038
4039         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4040         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4041
4042         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4043         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4044         assert_eq!(reestablish_1.len(), 1);
4045         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4046         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4047         assert_eq!(reestablish_2.len(), 1);
4048
4049         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4050         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4051         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4052         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4053
4054         assert!(as_resp.0.is_none());
4055         assert!(bs_resp.0.is_none());
4056
4057         assert!(bs_resp.1.is_none());
4058         assert!(bs_resp.2.is_none());
4059
4060         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4061
4062         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4063         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4064         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4065         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4066         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4067         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4068         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4069         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4070         // No commitment_signed so get_event_msg's assert(len == 1) passes
4071         check_added_monitors!(nodes[1], 1);
4072
4073         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4074         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4075         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4076         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4077         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4078         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4079         assert!(bs_second_commitment_signed.update_fee.is_none());
4080         check_added_monitors!(nodes[1], 1);
4081
4082         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4083         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4084         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4085         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4086         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4087         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4088         assert!(as_commitment_signed.update_fee.is_none());
4089         check_added_monitors!(nodes[0], 1);
4090
4091         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4092         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4093         // No commitment_signed so get_event_msg's assert(len == 1) passes
4094         check_added_monitors!(nodes[0], 1);
4095
4096         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4097         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4098         // No commitment_signed so get_event_msg's assert(len == 1) passes
4099         check_added_monitors!(nodes[1], 1);
4100
4101         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4102         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4103         check_added_monitors!(nodes[1], 1);
4104
4105         expect_pending_htlcs_forwardable!(nodes[1]);
4106
4107         let events_5 = nodes[1].node.get_and_clear_pending_events();
4108         assert_eq!(events_5.len(), 1);
4109         match events_5[0] {
4110                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4111                         assert_eq!(payment_hash_2, *payment_hash);
4112                         match &purpose {
4113                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4114                                         assert!(payment_preimage.is_none());
4115                                         assert_eq!(payment_secret_2, *payment_secret);
4116                                 },
4117                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4118                         }
4119                 },
4120                 _ => panic!("Unexpected event"),
4121         }
4122
4123         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4124         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4125         check_added_monitors!(nodes[0], 1);
4126
4127         expect_payment_path_successful!(nodes[0]);
4128         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4129 }
4130
4131 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4132         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4133         // to avoid our counterparty failing the channel.
4134         let chanmon_cfgs = create_chanmon_cfgs(2);
4135         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4136         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4137         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4138
4139         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4140
4141         let our_payment_hash = if send_partial_mpp {
4142                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4143                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4144                 // indicates there are more HTLCs coming.
4145                 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.
4146                 let payment_id = PaymentId([42; 32]);
4147                 nodes[0].node.send_payment_along_path(&route.paths[0], &route.payment_params, &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
4148                 check_added_monitors!(nodes[0], 1);
4149                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4150                 assert_eq!(events.len(), 1);
4151                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4152                 // hop should *not* yet generate any PaymentReceived event(s).
4153                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4154                 our_payment_hash
4155         } else {
4156                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4157         };
4158
4159         let mut block = Block {
4160                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4161                 txdata: vec![],
4162         };
4163         connect_block(&nodes[0], &block);
4164         connect_block(&nodes[1], &block);
4165         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4166         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4167                 block.header.prev_blockhash = block.block_hash();
4168                 connect_block(&nodes[0], &block);
4169                 connect_block(&nodes[1], &block);
4170         }
4171
4172         expect_pending_htlcs_forwardable!(nodes[1]);
4173
4174         check_added_monitors!(nodes[1], 1);
4175         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4176         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4177         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4178         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4179         assert!(htlc_timeout_updates.update_fee.is_none());
4180
4181         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4182         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4183         // 100_000 msat as u64, followed by the height at which we failed back above
4184         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4185         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4186         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4187 }
4188
4189 #[test]
4190 fn test_htlc_timeout() {
4191         do_test_htlc_timeout(true);
4192         do_test_htlc_timeout(false);
4193 }
4194
4195 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4196         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4197         let chanmon_cfgs = create_chanmon_cfgs(3);
4198         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4199         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4200         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4201         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4202         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4203
4204         // Make sure all nodes are at the same starting height
4205         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4206         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4207         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4208
4209         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4210         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4211         {
4212                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4213         }
4214         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4215         check_added_monitors!(nodes[1], 1);
4216
4217         // Now attempt to route a second payment, which should be placed in the holding cell
4218         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4219         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4220         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4221         if forwarded_htlc {
4222                 check_added_monitors!(nodes[0], 1);
4223                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4224                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4225                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4226                 expect_pending_htlcs_forwardable!(nodes[1]);
4227         }
4228         check_added_monitors!(nodes[1], 0);
4229
4230         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4231         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4232         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4233         connect_blocks(&nodes[1], 1);
4234
4235         if forwarded_htlc {
4236                 expect_pending_htlcs_forwardable!(nodes[1]);
4237                 check_added_monitors!(nodes[1], 1);
4238                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4239                 assert_eq!(fail_commit.len(), 1);
4240                 match fail_commit[0] {
4241                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4242                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4243                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4244                         },
4245                         _ => unreachable!(),
4246                 }
4247                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4248         } else {
4249                 let events = nodes[1].node.get_and_clear_pending_events();
4250                 assert_eq!(events.len(), 2);
4251                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4252                         assert_eq!(*payment_hash, second_payment_hash);
4253                 } else { panic!("Unexpected event"); }
4254                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4255                         assert_eq!(*payment_hash, second_payment_hash);
4256                 } else { panic!("Unexpected event"); }
4257         }
4258 }
4259
4260 #[test]
4261 fn test_holding_cell_htlc_add_timeouts() {
4262         do_test_holding_cell_htlc_add_timeouts(false);
4263         do_test_holding_cell_htlc_add_timeouts(true);
4264 }
4265
4266 #[test]
4267 fn test_no_txn_manager_serialize_deserialize() {
4268         let chanmon_cfgs = create_chanmon_cfgs(2);
4269         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4270         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4271         let logger: test_utils::TestLogger;
4272         let fee_estimator: test_utils::TestFeeEstimator;
4273         let persister: test_utils::TestPersister;
4274         let new_chain_monitor: test_utils::TestChainMonitor;
4275         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4276         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4277
4278         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4279
4280         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4281
4282         let nodes_0_serialized = nodes[0].node.encode();
4283         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4284         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4285                 .write(&mut chan_0_monitor_serialized).unwrap();
4286
4287         logger = test_utils::TestLogger::new();
4288         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4289         persister = test_utils::TestPersister::new();
4290         let keys_manager = &chanmon_cfgs[0].keys_manager;
4291         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4292         nodes[0].chain_monitor = &new_chain_monitor;
4293         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4294         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4295                 &mut chan_0_monitor_read, keys_manager).unwrap();
4296         assert!(chan_0_monitor_read.is_empty());
4297
4298         let mut nodes_0_read = &nodes_0_serialized[..];
4299         let config = UserConfig::default();
4300         let (_, nodes_0_deserialized_tmp) = {
4301                 let mut channel_monitors = HashMap::new();
4302                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4303                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4304                         default_config: config,
4305                         keys_manager,
4306                         fee_estimator: &fee_estimator,
4307                         chain_monitor: nodes[0].chain_monitor,
4308                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4309                         logger: &logger,
4310                         channel_monitors,
4311                 }).unwrap()
4312         };
4313         nodes_0_deserialized = nodes_0_deserialized_tmp;
4314         assert!(nodes_0_read.is_empty());
4315
4316         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4317         nodes[0].node = &nodes_0_deserialized;
4318         assert_eq!(nodes[0].node.list_channels().len(), 1);
4319         check_added_monitors!(nodes[0], 1);
4320
4321         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4322         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4323         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4324         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4325
4326         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4327         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4328         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4329         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4330
4331         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4332         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4333         for node in nodes.iter() {
4334                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4335                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4336                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4337         }
4338
4339         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4340 }
4341
4342 #[test]
4343 fn test_manager_serialize_deserialize_events() {
4344         // This test makes sure the events field in ChannelManager survives de/serialization
4345         let chanmon_cfgs = create_chanmon_cfgs(2);
4346         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4347         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4348         let fee_estimator: test_utils::TestFeeEstimator;
4349         let persister: test_utils::TestPersister;
4350         let logger: test_utils::TestLogger;
4351         let new_chain_monitor: test_utils::TestChainMonitor;
4352         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4353         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4354
4355         // Start creating a channel, but stop right before broadcasting the funding transaction
4356         let channel_value = 100000;
4357         let push_msat = 10001;
4358         let a_flags = InitFeatures::known();
4359         let b_flags = InitFeatures::known();
4360         let node_a = nodes.remove(0);
4361         let node_b = nodes.remove(0);
4362         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4363         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()));
4364         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()));
4365
4366         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4367
4368         node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4369         check_added_monitors!(node_a, 0);
4370
4371         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()));
4372         {
4373                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4374                 assert_eq!(added_monitors.len(), 1);
4375                 assert_eq!(added_monitors[0].0, funding_output);
4376                 added_monitors.clear();
4377         }
4378
4379         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4380         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4381         {
4382                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4383                 assert_eq!(added_monitors.len(), 1);
4384                 assert_eq!(added_monitors[0].0, funding_output);
4385                 added_monitors.clear();
4386         }
4387         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4388
4389         nodes.push(node_a);
4390         nodes.push(node_b);
4391
4392         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4393         let nodes_0_serialized = nodes[0].node.encode();
4394         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4395         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4396
4397         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4398         logger = test_utils::TestLogger::new();
4399         persister = test_utils::TestPersister::new();
4400         let keys_manager = &chanmon_cfgs[0].keys_manager;
4401         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4402         nodes[0].chain_monitor = &new_chain_monitor;
4403         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4404         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4405                 &mut chan_0_monitor_read, keys_manager).unwrap();
4406         assert!(chan_0_monitor_read.is_empty());
4407
4408         let mut nodes_0_read = &nodes_0_serialized[..];
4409         let config = UserConfig::default();
4410         let (_, nodes_0_deserialized_tmp) = {
4411                 let mut channel_monitors = HashMap::new();
4412                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4413                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4414                         default_config: config,
4415                         keys_manager,
4416                         fee_estimator: &fee_estimator,
4417                         chain_monitor: nodes[0].chain_monitor,
4418                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4419                         logger: &logger,
4420                         channel_monitors,
4421                 }).unwrap()
4422         };
4423         nodes_0_deserialized = nodes_0_deserialized_tmp;
4424         assert!(nodes_0_read.is_empty());
4425
4426         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4427
4428         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4429         nodes[0].node = &nodes_0_deserialized;
4430
4431         // After deserializing, make sure the funding_transaction is still held by the channel manager
4432         let events_4 = nodes[0].node.get_and_clear_pending_events();
4433         assert_eq!(events_4.len(), 0);
4434         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4435         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4436
4437         // Make sure the channel is functioning as though the de/serialization never happened
4438         assert_eq!(nodes[0].node.list_channels().len(), 1);
4439         check_added_monitors!(nodes[0], 1);
4440
4441         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4442         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4443         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4444         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4445
4446         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4447         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4448         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4449         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4450
4451         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4452         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4453         for node in nodes.iter() {
4454                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4455                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4456                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4457         }
4458
4459         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4460 }
4461
4462 #[test]
4463 fn test_simple_manager_serialize_deserialize() {
4464         let chanmon_cfgs = create_chanmon_cfgs(2);
4465         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4466         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4467         let logger: test_utils::TestLogger;
4468         let fee_estimator: test_utils::TestFeeEstimator;
4469         let persister: test_utils::TestPersister;
4470         let new_chain_monitor: test_utils::TestChainMonitor;
4471         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4472         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4473         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4474
4475         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4476         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4477
4478         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4479
4480         let nodes_0_serialized = nodes[0].node.encode();
4481         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4482         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4483
4484         logger = test_utils::TestLogger::new();
4485         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4486         persister = test_utils::TestPersister::new();
4487         let keys_manager = &chanmon_cfgs[0].keys_manager;
4488         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4489         nodes[0].chain_monitor = &new_chain_monitor;
4490         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4491         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4492                 &mut chan_0_monitor_read, keys_manager).unwrap();
4493         assert!(chan_0_monitor_read.is_empty());
4494
4495         let mut nodes_0_read = &nodes_0_serialized[..];
4496         let (_, nodes_0_deserialized_tmp) = {
4497                 let mut channel_monitors = HashMap::new();
4498                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4499                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4500                         default_config: UserConfig::default(),
4501                         keys_manager,
4502                         fee_estimator: &fee_estimator,
4503                         chain_monitor: nodes[0].chain_monitor,
4504                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4505                         logger: &logger,
4506                         channel_monitors,
4507                 }).unwrap()
4508         };
4509         nodes_0_deserialized = nodes_0_deserialized_tmp;
4510         assert!(nodes_0_read.is_empty());
4511
4512         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4513         nodes[0].node = &nodes_0_deserialized;
4514         check_added_monitors!(nodes[0], 1);
4515
4516         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4517
4518         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4519         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4520 }
4521
4522 #[test]
4523 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4524         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4525         let chanmon_cfgs = create_chanmon_cfgs(4);
4526         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4527         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4528         let logger: test_utils::TestLogger;
4529         let fee_estimator: test_utils::TestFeeEstimator;
4530         let persister: test_utils::TestPersister;
4531         let new_chain_monitor: test_utils::TestChainMonitor;
4532         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4533         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4534         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4535         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4536         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4537
4538         let mut node_0_stale_monitors_serialized = Vec::new();
4539         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4540                 let mut writer = test_utils::TestVecWriter(Vec::new());
4541                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4542                 node_0_stale_monitors_serialized.push(writer.0);
4543         }
4544
4545         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4546
4547         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4548         let nodes_0_serialized = nodes[0].node.encode();
4549
4550         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4551         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4552         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4553         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4554
4555         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4556         // nodes[3])
4557         let mut node_0_monitors_serialized = Vec::new();
4558         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4559                 let mut writer = test_utils::TestVecWriter(Vec::new());
4560                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4561                 node_0_monitors_serialized.push(writer.0);
4562         }
4563
4564         logger = test_utils::TestLogger::new();
4565         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4566         persister = test_utils::TestPersister::new();
4567         let keys_manager = &chanmon_cfgs[0].keys_manager;
4568         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4569         nodes[0].chain_monitor = &new_chain_monitor;
4570
4571
4572         let mut node_0_stale_monitors = Vec::new();
4573         for serialized in node_0_stale_monitors_serialized.iter() {
4574                 let mut read = &serialized[..];
4575                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4576                 assert!(read.is_empty());
4577                 node_0_stale_monitors.push(monitor);
4578         }
4579
4580         let mut node_0_monitors = Vec::new();
4581         for serialized in node_0_monitors_serialized.iter() {
4582                 let mut read = &serialized[..];
4583                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4584                 assert!(read.is_empty());
4585                 node_0_monitors.push(monitor);
4586         }
4587
4588         let mut nodes_0_read = &nodes_0_serialized[..];
4589         if let Err(msgs::DecodeError::InvalidValue) =
4590                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4591                 default_config: UserConfig::default(),
4592                 keys_manager,
4593                 fee_estimator: &fee_estimator,
4594                 chain_monitor: nodes[0].chain_monitor,
4595                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4596                 logger: &logger,
4597                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4598         }) { } else {
4599                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4600         };
4601
4602         let mut nodes_0_read = &nodes_0_serialized[..];
4603         let (_, nodes_0_deserialized_tmp) =
4604                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4605                 default_config: UserConfig::default(),
4606                 keys_manager,
4607                 fee_estimator: &fee_estimator,
4608                 chain_monitor: nodes[0].chain_monitor,
4609                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4610                 logger: &logger,
4611                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4612         }).unwrap();
4613         nodes_0_deserialized = nodes_0_deserialized_tmp;
4614         assert!(nodes_0_read.is_empty());
4615
4616         { // Channel close should result in a commitment tx
4617                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4618                 assert_eq!(txn.len(), 1);
4619                 check_spends!(txn[0], funding_tx);
4620                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4621         }
4622
4623         for monitor in node_0_monitors.drain(..) {
4624                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4625                 check_added_monitors!(nodes[0], 1);
4626         }
4627         nodes[0].node = &nodes_0_deserialized;
4628         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4629
4630         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4631         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4632         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4633         //... and we can even still claim the payment!
4634         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4635
4636         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4637         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4638         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4639         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4640         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4641         assert_eq!(msg_events.len(), 1);
4642         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4643                 match action {
4644                         &ErrorAction::SendErrorMessage { ref msg } => {
4645                                 assert_eq!(msg.channel_id, channel_id);
4646                         },
4647                         _ => panic!("Unexpected event!"),
4648                 }
4649         }
4650 }
4651
4652 macro_rules! check_spendable_outputs {
4653         ($node: expr, $keysinterface: expr) => {
4654                 {
4655                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4656                         let mut txn = Vec::new();
4657                         let mut all_outputs = Vec::new();
4658                         let secp_ctx = Secp256k1::new();
4659                         for event in events.drain(..) {
4660                                 match event {
4661                                         Event::SpendableOutputs { mut outputs } => {
4662                                                 for outp in outputs.drain(..) {
4663                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4664                                                         all_outputs.push(outp);
4665                                                 }
4666                                         },
4667                                         _ => panic!("Unexpected event"),
4668                                 };
4669                         }
4670                         if all_outputs.len() > 1 {
4671                                 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) {
4672                                         txn.push(tx);
4673                                 }
4674                         }
4675                         txn
4676                 }
4677         }
4678 }
4679
4680 #[test]
4681 fn test_claim_sizeable_push_msat() {
4682         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4683         let chanmon_cfgs = create_chanmon_cfgs(2);
4684         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4685         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4686         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4687
4688         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4689         nodes[1].node.force_close_channel(&chan.2).unwrap();
4690         check_closed_broadcast!(nodes[1], true);
4691         check_added_monitors!(nodes[1], 1);
4692         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4693         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4694         assert_eq!(node_txn.len(), 1);
4695         check_spends!(node_txn[0], chan.3);
4696         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
4697
4698         mine_transaction(&nodes[1], &node_txn[0]);
4699         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4700
4701         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4702         assert_eq!(spend_txn.len(), 1);
4703         assert_eq!(spend_txn[0].input.len(), 1);
4704         check_spends!(spend_txn[0], node_txn[0]);
4705         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4706 }
4707
4708 #[test]
4709 fn test_claim_on_remote_sizeable_push_msat() {
4710         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4711         // to_remote output is encumbered by a P2WPKH
4712         let chanmon_cfgs = create_chanmon_cfgs(2);
4713         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4714         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4715         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4716
4717         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4718         nodes[0].node.force_close_channel(&chan.2).unwrap();
4719         check_closed_broadcast!(nodes[0], true);
4720         check_added_monitors!(nodes[0], 1);
4721         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4722
4723         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4724         assert_eq!(node_txn.len(), 1);
4725         check_spends!(node_txn[0], chan.3);
4726         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
4727
4728         mine_transaction(&nodes[1], &node_txn[0]);
4729         check_closed_broadcast!(nodes[1], true);
4730         check_added_monitors!(nodes[1], 1);
4731         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4732         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4733
4734         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4735         assert_eq!(spend_txn.len(), 1);
4736         check_spends!(spend_txn[0], node_txn[0]);
4737 }
4738
4739 #[test]
4740 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4741         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4742         // to_remote output is encumbered by a P2WPKH
4743
4744         let chanmon_cfgs = create_chanmon_cfgs(2);
4745         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4746         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4747         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4748
4749         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4750         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4751         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4752         assert_eq!(revoked_local_txn[0].input.len(), 1);
4753         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4754
4755         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4756         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4757         check_closed_broadcast!(nodes[1], true);
4758         check_added_monitors!(nodes[1], 1);
4759         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4760
4761         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4762         mine_transaction(&nodes[1], &node_txn[0]);
4763         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4764
4765         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4766         assert_eq!(spend_txn.len(), 3);
4767         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4768         check_spends!(spend_txn[1], node_txn[0]);
4769         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4770 }
4771
4772 #[test]
4773 fn test_static_spendable_outputs_preimage_tx() {
4774         let chanmon_cfgs = create_chanmon_cfgs(2);
4775         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4776         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4777         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4778
4779         // Create some initial channels
4780         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4781
4782         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4783
4784         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4785         assert_eq!(commitment_tx[0].input.len(), 1);
4786         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4787
4788         // Settle A's commitment tx on B's chain
4789         assert!(nodes[1].node.claim_funds(payment_preimage));
4790         check_added_monitors!(nodes[1], 1);
4791         mine_transaction(&nodes[1], &commitment_tx[0]);
4792         check_added_monitors!(nodes[1], 1);
4793         let events = nodes[1].node.get_and_clear_pending_msg_events();
4794         match events[0] {
4795                 MessageSendEvent::UpdateHTLCs { .. } => {},
4796                 _ => panic!("Unexpected event"),
4797         }
4798         match events[1] {
4799                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4800                 _ => panic!("Unexepected event"),
4801         }
4802
4803         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4804         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4805         assert_eq!(node_txn.len(), 3);
4806         check_spends!(node_txn[0], commitment_tx[0]);
4807         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4808         check_spends!(node_txn[1], chan_1.3);
4809         check_spends!(node_txn[2], node_txn[1]);
4810
4811         mine_transaction(&nodes[1], &node_txn[0]);
4812         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4813         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4814
4815         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4816         assert_eq!(spend_txn.len(), 1);
4817         check_spends!(spend_txn[0], node_txn[0]);
4818 }
4819
4820 #[test]
4821 fn test_static_spendable_outputs_timeout_tx() {
4822         let chanmon_cfgs = create_chanmon_cfgs(2);
4823         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4824         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4825         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4826
4827         // Create some initial channels
4828         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4829
4830         // Rebalance the network a bit by relaying one payment through all the channels ...
4831         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4832
4833         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4834
4835         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4836         assert_eq!(commitment_tx[0].input.len(), 1);
4837         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4838
4839         // Settle A's commitment tx on B' chain
4840         mine_transaction(&nodes[1], &commitment_tx[0]);
4841         check_added_monitors!(nodes[1], 1);
4842         let events = nodes[1].node.get_and_clear_pending_msg_events();
4843         match events[0] {
4844                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4845                 _ => panic!("Unexpected event"),
4846         }
4847         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4848
4849         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4850         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4851         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4852         check_spends!(node_txn[0], chan_1.3.clone());
4853         check_spends!(node_txn[1],  commitment_tx[0].clone());
4854         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4855
4856         mine_transaction(&nodes[1], &node_txn[1]);
4857         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4858         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4859         expect_payment_failed!(nodes[1], our_payment_hash, true);
4860
4861         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4862         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4863         check_spends!(spend_txn[0], commitment_tx[0]);
4864         check_spends!(spend_txn[1], node_txn[1]);
4865         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4866 }
4867
4868 #[test]
4869 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4870         let chanmon_cfgs = create_chanmon_cfgs(2);
4871         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4872         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4873         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4874
4875         // Create some initial channels
4876         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4877
4878         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4879         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4880         assert_eq!(revoked_local_txn[0].input.len(), 1);
4881         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4882
4883         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4884
4885         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4886         check_closed_broadcast!(nodes[1], true);
4887         check_added_monitors!(nodes[1], 1);
4888         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4889
4890         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4891         assert_eq!(node_txn.len(), 2);
4892         assert_eq!(node_txn[0].input.len(), 2);
4893         check_spends!(node_txn[0], revoked_local_txn[0]);
4894
4895         mine_transaction(&nodes[1], &node_txn[0]);
4896         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4897
4898         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4899         assert_eq!(spend_txn.len(), 1);
4900         check_spends!(spend_txn[0], node_txn[0]);
4901 }
4902
4903 #[test]
4904 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4905         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4906         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4907         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4908         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4909         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4910
4911         // Create some initial channels
4912         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4913
4914         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4915         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4916         assert_eq!(revoked_local_txn[0].input.len(), 1);
4917         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4918
4919         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4920
4921         // A will generate HTLC-Timeout from revoked commitment tx
4922         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4923         check_closed_broadcast!(nodes[0], true);
4924         check_added_monitors!(nodes[0], 1);
4925         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4926         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4927
4928         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4929         assert_eq!(revoked_htlc_txn.len(), 2);
4930         check_spends!(revoked_htlc_txn[0], chan_1.3);
4931         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4932         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4933         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4934         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4935
4936         // B will generate justice tx from A's revoked commitment/HTLC tx
4937         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4938         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4939         check_closed_broadcast!(nodes[1], true);
4940         check_added_monitors!(nodes[1], 1);
4941         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4942
4943         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4944         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4945         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4946         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4947         // transactions next...
4948         assert_eq!(node_txn[0].input.len(), 3);
4949         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4950
4951         assert_eq!(node_txn[1].input.len(), 2);
4952         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4953         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4954                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4955         } else {
4956                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4957                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4958         }
4959
4960         assert_eq!(node_txn[2].input.len(), 1);
4961         check_spends!(node_txn[2], chan_1.3);
4962
4963         mine_transaction(&nodes[1], &node_txn[1]);
4964         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4965
4966         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4967         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4968         assert_eq!(spend_txn.len(), 1);
4969         assert_eq!(spend_txn[0].input.len(), 1);
4970         check_spends!(spend_txn[0], node_txn[1]);
4971 }
4972
4973 #[test]
4974 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4975         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4976         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4977         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4978         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4979         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4980
4981         // Create some initial channels
4982         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4983
4984         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4985         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4986         assert_eq!(revoked_local_txn[0].input.len(), 1);
4987         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4988
4989         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4990         assert_eq!(revoked_local_txn[0].output.len(), 2);
4991
4992         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4993
4994         // B will generate HTLC-Success from revoked commitment tx
4995         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4996         check_closed_broadcast!(nodes[1], true);
4997         check_added_monitors!(nodes[1], 1);
4998         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4999         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5000
5001         assert_eq!(revoked_htlc_txn.len(), 2);
5002         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5003         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5004         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5005
5006         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5007         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5008         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5009
5010         // A will generate justice tx from B's revoked commitment/HTLC tx
5011         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5012         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5013         check_closed_broadcast!(nodes[0], true);
5014         check_added_monitors!(nodes[0], 1);
5015         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5016
5017         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5018         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5019
5020         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5021         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5022         // transactions next...
5023         assert_eq!(node_txn[0].input.len(), 2);
5024         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5025         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5026                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5027         } else {
5028                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5029                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5030         }
5031
5032         assert_eq!(node_txn[1].input.len(), 1);
5033         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5034
5035         check_spends!(node_txn[2], chan_1.3);
5036
5037         mine_transaction(&nodes[0], &node_txn[1]);
5038         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5039
5040         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5041         // didn't try to generate any new transactions.
5042
5043         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5044         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5045         assert_eq!(spend_txn.len(), 3);
5046         assert_eq!(spend_txn[0].input.len(), 1);
5047         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5048         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5049         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5050         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5051 }
5052
5053 #[test]
5054 fn test_onchain_to_onchain_claim() {
5055         // Test that in case of channel closure, we detect the state of output and claim HTLC
5056         // on downstream peer's remote commitment tx.
5057         // First, have C claim an HTLC against its own latest commitment transaction.
5058         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5059         // channel.
5060         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5061         // gets broadcast.
5062
5063         let chanmon_cfgs = create_chanmon_cfgs(3);
5064         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5065         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5066         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5067
5068         // Create some initial channels
5069         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5070         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5071
5072         // Ensure all nodes are at the same height
5073         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5074         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5075         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5076         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5077
5078         // Rebalance the network a bit by relaying one payment through all the channels ...
5079         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5080         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5081
5082         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5083         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5084         check_spends!(commitment_tx[0], chan_2.3);
5085         nodes[2].node.claim_funds(payment_preimage);
5086         check_added_monitors!(nodes[2], 1);
5087         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5088         assert!(updates.update_add_htlcs.is_empty());
5089         assert!(updates.update_fail_htlcs.is_empty());
5090         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5091         assert!(updates.update_fail_malformed_htlcs.is_empty());
5092
5093         mine_transaction(&nodes[2], &commitment_tx[0]);
5094         check_closed_broadcast!(nodes[2], true);
5095         check_added_monitors!(nodes[2], 1);
5096         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5097
5098         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5099         assert_eq!(c_txn.len(), 3);
5100         assert_eq!(c_txn[0], c_txn[2]);
5101         assert_eq!(commitment_tx[0], c_txn[1]);
5102         check_spends!(c_txn[1], chan_2.3);
5103         check_spends!(c_txn[2], c_txn[1]);
5104         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5105         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5106         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5107         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5108
5109         // 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
5110         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5111         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5112         check_added_monitors!(nodes[1], 1);
5113         let events = nodes[1].node.get_and_clear_pending_events();
5114         assert_eq!(events.len(), 2);
5115         match events[0] {
5116                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5117                 _ => panic!("Unexpected event"),
5118         }
5119         match events[1] {
5120                 Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
5121                         assert_eq!(fee_earned_msat, Some(1000));
5122                         assert_eq!(source_channel_id, Some(chan_1.2));
5123                         assert_eq!(claim_from_onchain_tx, true);
5124                 },
5125                 _ => panic!("Unexpected event"),
5126         }
5127         {
5128                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5129                 // ChannelMonitor: claim tx
5130                 assert_eq!(b_txn.len(), 1);
5131                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5132                 b_txn.clear();
5133         }
5134         check_added_monitors!(nodes[1], 1);
5135         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5136         assert_eq!(msg_events.len(), 3);
5137         match msg_events[0] {
5138                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5139                 _ => panic!("Unexpected event"),
5140         }
5141         match msg_events[1] {
5142                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5143                 _ => panic!("Unexpected event"),
5144         }
5145         match msg_events[2] {
5146                 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, .. } } => {
5147                         assert!(update_add_htlcs.is_empty());
5148                         assert!(update_fail_htlcs.is_empty());
5149                         assert_eq!(update_fulfill_htlcs.len(), 1);
5150                         assert!(update_fail_malformed_htlcs.is_empty());
5151                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5152                 },
5153                 _ => panic!("Unexpected event"),
5154         };
5155         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5156         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5157         mine_transaction(&nodes[1], &commitment_tx[0]);
5158         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5159         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5160         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5161         assert_eq!(b_txn.len(), 3);
5162         check_spends!(b_txn[1], chan_1.3);
5163         check_spends!(b_txn[2], b_txn[1]);
5164         check_spends!(b_txn[0], commitment_tx[0]);
5165         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5166         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5167         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5168
5169         check_closed_broadcast!(nodes[1], true);
5170         check_added_monitors!(nodes[1], 1);
5171 }
5172
5173 #[test]
5174 fn test_duplicate_payment_hash_one_failure_one_success() {
5175         // Topology : A --> B --> C --> D
5176         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5177         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5178         // we forward one of the payments onwards to D.
5179         let chanmon_cfgs = create_chanmon_cfgs(4);
5180         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5181         // When this test was written, the default base fee floated based on the HTLC count.
5182         // It is now fixed, so we simply set the fee to the expected value here.
5183         let mut config = test_default_channel_config();
5184         config.channel_options.forwarding_fee_base_msat = 196;
5185         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5186                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5187         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5188
5189         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5190         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5191         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5192
5193         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5194         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5195         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5196         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5197         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5198
5199         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5200
5201         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5202         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5203         // script push size limit so that the below script length checks match
5204         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5205         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5206                 .with_features(InvoiceFeatures::known());
5207         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5208         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5209
5210         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5211         assert_eq!(commitment_txn[0].input.len(), 1);
5212         check_spends!(commitment_txn[0], chan_2.3);
5213
5214         mine_transaction(&nodes[1], &commitment_txn[0]);
5215         check_closed_broadcast!(nodes[1], true);
5216         check_added_monitors!(nodes[1], 1);
5217         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5218         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5219
5220         let htlc_timeout_tx;
5221         { // Extract one of the two HTLC-Timeout transaction
5222                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5223                 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5224                 assert_eq!(node_txn.len(), 4);
5225                 check_spends!(node_txn[0], chan_2.3);
5226
5227                 check_spends!(node_txn[1], commitment_txn[0]);
5228                 assert_eq!(node_txn[1].input.len(), 1);
5229                 check_spends!(node_txn[2], commitment_txn[0]);
5230                 assert_eq!(node_txn[2].input.len(), 1);
5231                 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5232                 check_spends!(node_txn[3], commitment_txn[0]);
5233                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5234
5235                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5236                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5237                 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5238                 htlc_timeout_tx = node_txn[1].clone();
5239         }
5240
5241         nodes[2].node.claim_funds(our_payment_preimage);
5242         mine_transaction(&nodes[2], &commitment_txn[0]);
5243         check_added_monitors!(nodes[2], 2);
5244         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5245         let events = nodes[2].node.get_and_clear_pending_msg_events();
5246         match events[0] {
5247                 MessageSendEvent::UpdateHTLCs { .. } => {},
5248                 _ => panic!("Unexpected event"),
5249         }
5250         match events[1] {
5251                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5252                 _ => panic!("Unexepected event"),
5253         }
5254         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5255         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)
5256         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5257         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5258         assert_eq!(htlc_success_txn[0].input.len(), 1);
5259         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5260         assert_eq!(htlc_success_txn[1].input.len(), 1);
5261         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5262         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5263         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5264         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5265         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5266         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5267
5268         mine_transaction(&nodes[1], &htlc_timeout_tx);
5269         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5270         expect_pending_htlcs_forwardable!(nodes[1]);
5271         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5272         assert!(htlc_updates.update_add_htlcs.is_empty());
5273         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5274         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5275         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5276         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5277         check_added_monitors!(nodes[1], 1);
5278
5279         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5280         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5281         {
5282                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5283         }
5284         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5285
5286         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5287         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5288         // and nodes[2] fee) is rounded down and then claimed in full.
5289         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5290         expect_payment_forwarded!(nodes[1], nodes[0], Some(196*2), true);
5291         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5292         assert!(updates.update_add_htlcs.is_empty());
5293         assert!(updates.update_fail_htlcs.is_empty());
5294         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5295         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5296         assert!(updates.update_fail_malformed_htlcs.is_empty());
5297         check_added_monitors!(nodes[1], 1);
5298
5299         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5300         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5301
5302         let events = nodes[0].node.get_and_clear_pending_events();
5303         match events[0] {
5304                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5305                         assert_eq!(*payment_preimage, our_payment_preimage);
5306                         assert_eq!(*payment_hash, duplicate_payment_hash);
5307                 }
5308                 _ => panic!("Unexpected event"),
5309         }
5310 }
5311
5312 #[test]
5313 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5314         let chanmon_cfgs = create_chanmon_cfgs(2);
5315         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5316         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5317         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5318
5319         // Create some initial channels
5320         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5321
5322         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5323         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5324         assert_eq!(local_txn.len(), 1);
5325         assert_eq!(local_txn[0].input.len(), 1);
5326         check_spends!(local_txn[0], chan_1.3);
5327
5328         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5329         nodes[1].node.claim_funds(payment_preimage);
5330         check_added_monitors!(nodes[1], 1);
5331         mine_transaction(&nodes[1], &local_txn[0]);
5332         check_added_monitors!(nodes[1], 1);
5333         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5334         let events = nodes[1].node.get_and_clear_pending_msg_events();
5335         match events[0] {
5336                 MessageSendEvent::UpdateHTLCs { .. } => {},
5337                 _ => panic!("Unexpected event"),
5338         }
5339         match events[1] {
5340                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5341                 _ => panic!("Unexepected event"),
5342         }
5343         let node_tx = {
5344                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5345                 assert_eq!(node_txn.len(), 3);
5346                 assert_eq!(node_txn[0], node_txn[2]);
5347                 assert_eq!(node_txn[1], local_txn[0]);
5348                 assert_eq!(node_txn[0].input.len(), 1);
5349                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5350                 check_spends!(node_txn[0], local_txn[0]);
5351                 node_txn[0].clone()
5352         };
5353
5354         mine_transaction(&nodes[1], &node_tx);
5355         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5356
5357         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5358         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5359         assert_eq!(spend_txn.len(), 1);
5360         assert_eq!(spend_txn[0].input.len(), 1);
5361         check_spends!(spend_txn[0], node_tx);
5362         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5363 }
5364
5365 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5366         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5367         // unrevoked commitment transaction.
5368         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5369         // a remote RAA before they could be failed backwards (and combinations thereof).
5370         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5371         // use the same payment hashes.
5372         // Thus, we use a six-node network:
5373         //
5374         // A \         / E
5375         //    - C - D -
5376         // B /         \ F
5377         // And test where C fails back to A/B when D announces its latest commitment transaction
5378         let chanmon_cfgs = create_chanmon_cfgs(6);
5379         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5380         // When this test was written, the default base fee floated based on the HTLC count.
5381         // It is now fixed, so we simply set the fee to the expected value here.
5382         let mut config = test_default_channel_config();
5383         config.channel_options.forwarding_fee_base_msat = 196;
5384         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5385                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5386         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5387
5388         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5389         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5390         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5391         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5392         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5393
5394         // Rebalance and check output sanity...
5395         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5396         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5397         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5398
5399         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5400         // 0th HTLC:
5401         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
5402         // 1st HTLC:
5403         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
5404         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5405         // 2nd HTLC:
5406         send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_1, nodes[5].node.create_inbound_payment_for_hash(payment_hash_1, None, 7200).unwrap()); // not added < dust limit + HTLC tx fee
5407         // 3rd HTLC:
5408         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_2, nodes[5].node.create_inbound_payment_for_hash(payment_hash_2, None, 7200).unwrap()); // not added < dust limit + HTLC tx fee
5409         // 4th HTLC:
5410         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5411         // 5th HTLC:
5412         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5413         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5414         // 6th HTLC:
5415         send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_3, nodes[5].node.create_inbound_payment_for_hash(payment_hash_3, None, 7200).unwrap());
5416         // 7th HTLC:
5417         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_4, nodes[5].node.create_inbound_payment_for_hash(payment_hash_4, None, 7200).unwrap());
5418
5419         // 8th HTLC:
5420         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5421         // 9th HTLC:
5422         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5423         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_5, nodes[5].node.create_inbound_payment_for_hash(payment_hash_5, None, 7200).unwrap()); // not added < dust limit + HTLC tx fee
5424
5425         // 10th HTLC:
5426         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
5427         // 11th HTLC:
5428         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5429         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_6, nodes[5].node.create_inbound_payment_for_hash(payment_hash_6, None, 7200).unwrap());
5430
5431         // Double-check that six of the new HTLC were added
5432         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5433         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5434         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5435         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5436
5437         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5438         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5439         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5440         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5441         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5442         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5443         check_added_monitors!(nodes[4], 0);
5444         expect_pending_htlcs_forwardable!(nodes[4]);
5445         check_added_monitors!(nodes[4], 1);
5446
5447         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5448         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5449         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5450         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5451         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5452         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5453
5454         // Fail 3rd below-dust and 7th above-dust HTLCs
5455         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5456         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5457         check_added_monitors!(nodes[5], 0);
5458         expect_pending_htlcs_forwardable!(nodes[5]);
5459         check_added_monitors!(nodes[5], 1);
5460
5461         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5462         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5463         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5464         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5465
5466         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5467
5468         expect_pending_htlcs_forwardable!(nodes[3]);
5469         check_added_monitors!(nodes[3], 1);
5470         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5471         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5472         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5473         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5474         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5475         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5476         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5477         if deliver_last_raa {
5478                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5479         } else {
5480                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5481         }
5482
5483         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5484         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5485         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5486         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5487         //
5488         // We now broadcast the latest commitment transaction, which *should* result in failures for
5489         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5490         // the non-broadcast above-dust HTLCs.
5491         //
5492         // Alternatively, we may broadcast the previous commitment transaction, which should only
5493         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5494         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5495
5496         if announce_latest {
5497                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5498         } else {
5499                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5500         }
5501         let events = nodes[2].node.get_and_clear_pending_events();
5502         let close_event = if deliver_last_raa {
5503                 assert_eq!(events.len(), 2);
5504                 events[1].clone()
5505         } else {
5506                 assert_eq!(events.len(), 1);
5507                 events[0].clone()
5508         };
5509         match close_event {
5510                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5511                 _ => panic!("Unexpected event"),
5512         }
5513
5514         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5515         check_closed_broadcast!(nodes[2], true);
5516         if deliver_last_raa {
5517                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5518         } else {
5519                 expect_pending_htlcs_forwardable!(nodes[2]);
5520         }
5521         check_added_monitors!(nodes[2], 3);
5522
5523         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5524         assert_eq!(cs_msgs.len(), 2);
5525         let mut a_done = false;
5526         for msg in cs_msgs {
5527                 match msg {
5528                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5529                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5530                                 // should be failed-backwards here.
5531                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5532                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5533                                         for htlc in &updates.update_fail_htlcs {
5534                                                 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 });
5535                                         }
5536                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5537                                         assert!(!a_done);
5538                                         a_done = true;
5539                                         &nodes[0]
5540                                 } else {
5541                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5542                                         for htlc in &updates.update_fail_htlcs {
5543                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5544                                         }
5545                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5546                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5547                                         &nodes[1]
5548                                 };
5549                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5550                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5551                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5552                                 if announce_latest {
5553                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5554                                         if *node_id == nodes[0].node.get_our_node_id() {
5555                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5556                                         }
5557                                 }
5558                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5559                         },
5560                         _ => panic!("Unexpected event"),
5561                 }
5562         }
5563
5564         let as_events = nodes[0].node.get_and_clear_pending_events();
5565         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5566         let mut as_failds = HashSet::new();
5567         let mut as_updates = 0;
5568         for event in as_events.iter() {
5569                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5570                         assert!(as_failds.insert(*payment_hash));
5571                         if *payment_hash != payment_hash_2 {
5572                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5573                         } else {
5574                                 assert!(!rejected_by_dest);
5575                         }
5576                         if network_update.is_some() {
5577                                 as_updates += 1;
5578                         }
5579                 } else { panic!("Unexpected event"); }
5580         }
5581         assert!(as_failds.contains(&payment_hash_1));
5582         assert!(as_failds.contains(&payment_hash_2));
5583         if announce_latest {
5584                 assert!(as_failds.contains(&payment_hash_3));
5585                 assert!(as_failds.contains(&payment_hash_5));
5586         }
5587         assert!(as_failds.contains(&payment_hash_6));
5588
5589         let bs_events = nodes[1].node.get_and_clear_pending_events();
5590         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5591         let mut bs_failds = HashSet::new();
5592         let mut bs_updates = 0;
5593         for event in bs_events.iter() {
5594                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5595                         assert!(bs_failds.insert(*payment_hash));
5596                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5597                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5598                         } else {
5599                                 assert!(!rejected_by_dest);
5600                         }
5601                         if network_update.is_some() {
5602                                 bs_updates += 1;
5603                         }
5604                 } else { panic!("Unexpected event"); }
5605         }
5606         assert!(bs_failds.contains(&payment_hash_1));
5607         assert!(bs_failds.contains(&payment_hash_2));
5608         if announce_latest {
5609                 assert!(bs_failds.contains(&payment_hash_4));
5610         }
5611         assert!(bs_failds.contains(&payment_hash_5));
5612
5613         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5614         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5615         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5616         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5617         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5618         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5619 }
5620
5621 #[test]
5622 fn test_fail_backwards_latest_remote_announce_a() {
5623         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5624 }
5625
5626 #[test]
5627 fn test_fail_backwards_latest_remote_announce_b() {
5628         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5629 }
5630
5631 #[test]
5632 fn test_fail_backwards_previous_remote_announce() {
5633         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5634         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5635         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5636 }
5637
5638 #[test]
5639 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5640         let chanmon_cfgs = create_chanmon_cfgs(2);
5641         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5642         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5643         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5644
5645         // Create some initial channels
5646         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5647
5648         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5649         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5650         assert_eq!(local_txn[0].input.len(), 1);
5651         check_spends!(local_txn[0], chan_1.3);
5652
5653         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5654         mine_transaction(&nodes[0], &local_txn[0]);
5655         check_closed_broadcast!(nodes[0], true);
5656         check_added_monitors!(nodes[0], 1);
5657         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5658         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5659
5660         let htlc_timeout = {
5661                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5662                 assert_eq!(node_txn.len(), 2);
5663                 check_spends!(node_txn[0], chan_1.3);
5664                 assert_eq!(node_txn[1].input.len(), 1);
5665                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5666                 check_spends!(node_txn[1], local_txn[0]);
5667                 node_txn[1].clone()
5668         };
5669
5670         mine_transaction(&nodes[0], &htlc_timeout);
5671         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5672         expect_payment_failed!(nodes[0], our_payment_hash, true);
5673
5674         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5675         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5676         assert_eq!(spend_txn.len(), 3);
5677         check_spends!(spend_txn[0], local_txn[0]);
5678         assert_eq!(spend_txn[1].input.len(), 1);
5679         check_spends!(spend_txn[1], htlc_timeout);
5680         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5681         assert_eq!(spend_txn[2].input.len(), 2);
5682         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5683         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5684                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5685 }
5686
5687 #[test]
5688 fn test_key_derivation_params() {
5689         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5690         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5691         // let us re-derive the channel key set to then derive a delayed_payment_key.
5692
5693         let chanmon_cfgs = create_chanmon_cfgs(3);
5694
5695         // We manually create the node configuration to backup the seed.
5696         let seed = [42; 32];
5697         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5698         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);
5699         let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chain_monitor, keys_manager: &keys_manager, network_graph: &chanmon_cfgs[0].network_graph, node_seed: seed, features: InitFeatures::known() };
5700         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5701         node_cfgs.remove(0);
5702         node_cfgs.insert(0, node);
5703
5704         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5705         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5706
5707         // Create some initial channels
5708         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5709         // for node 0
5710         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5711         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5712         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5713
5714         // Ensure all nodes are at the same height
5715         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5716         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5717         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5718         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5719
5720         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5721         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5722         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5723         assert_eq!(local_txn_1[0].input.len(), 1);
5724         check_spends!(local_txn_1[0], chan_1.3);
5725
5726         // We check funding pubkey are unique
5727         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]));
5728         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]));
5729         if from_0_funding_key_0 == from_1_funding_key_0
5730             || from_0_funding_key_0 == from_1_funding_key_1
5731             || from_0_funding_key_1 == from_1_funding_key_0
5732             || from_0_funding_key_1 == from_1_funding_key_1 {
5733                 panic!("Funding pubkeys aren't unique");
5734         }
5735
5736         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5737         mine_transaction(&nodes[0], &local_txn_1[0]);
5738         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5739         check_closed_broadcast!(nodes[0], true);
5740         check_added_monitors!(nodes[0], 1);
5741         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5742
5743         let htlc_timeout = {
5744                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5745                 assert_eq!(node_txn[1].input.len(), 1);
5746                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5747                 check_spends!(node_txn[1], local_txn_1[0]);
5748                 node_txn[1].clone()
5749         };
5750
5751         mine_transaction(&nodes[0], &htlc_timeout);
5752         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5753         expect_payment_failed!(nodes[0], our_payment_hash, true);
5754
5755         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5756         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5757         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5758         assert_eq!(spend_txn.len(), 3);
5759         check_spends!(spend_txn[0], local_txn_1[0]);
5760         assert_eq!(spend_txn[1].input.len(), 1);
5761         check_spends!(spend_txn[1], htlc_timeout);
5762         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5763         assert_eq!(spend_txn[2].input.len(), 2);
5764         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5765         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5766                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5767 }
5768
5769 #[test]
5770 fn test_static_output_closing_tx() {
5771         let chanmon_cfgs = create_chanmon_cfgs(2);
5772         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5773         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5774         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5775
5776         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5777
5778         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5779         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5780
5781         mine_transaction(&nodes[0], &closing_tx);
5782         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5783         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5784
5785         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5786         assert_eq!(spend_txn.len(), 1);
5787         check_spends!(spend_txn[0], closing_tx);
5788
5789         mine_transaction(&nodes[1], &closing_tx);
5790         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5791         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5792
5793         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5794         assert_eq!(spend_txn.len(), 1);
5795         check_spends!(spend_txn[0], closing_tx);
5796 }
5797
5798 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5799         let chanmon_cfgs = create_chanmon_cfgs(2);
5800         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5801         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5802         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5803         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5804
5805         let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5806
5807         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5808         // present in B's local commitment transaction, but none of A's commitment transactions.
5809         assert!(nodes[1].node.claim_funds(payment_preimage));
5810         check_added_monitors!(nodes[1], 1);
5811
5812         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5813         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5814         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5815
5816         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5817         check_added_monitors!(nodes[0], 1);
5818         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5819         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5820         check_added_monitors!(nodes[1], 1);
5821
5822         let starting_block = nodes[1].best_block_info();
5823         let mut block = Block {
5824                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5825                 txdata: vec![],
5826         };
5827         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5828                 connect_block(&nodes[1], &block);
5829                 block.header.prev_blockhash = block.block_hash();
5830         }
5831         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5832         check_closed_broadcast!(nodes[1], true);
5833         check_added_monitors!(nodes[1], 1);
5834         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5835 }
5836
5837 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5838         let chanmon_cfgs = create_chanmon_cfgs(2);
5839         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5840         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5841         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5842         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5843
5844         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5845         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5846         check_added_monitors!(nodes[0], 1);
5847
5848         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5849
5850         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5851         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5852         // to "time out" the HTLC.
5853
5854         let starting_block = nodes[1].best_block_info();
5855         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5856
5857         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5858                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5859                 header.prev_blockhash = header.block_hash();
5860         }
5861         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5862         check_closed_broadcast!(nodes[0], true);
5863         check_added_monitors!(nodes[0], 1);
5864         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5865 }
5866
5867 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5868         let chanmon_cfgs = create_chanmon_cfgs(3);
5869         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5870         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5871         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5872         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5873
5874         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5875         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5876         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5877         // actually revoked.
5878         let htlc_value = if use_dust { 50000 } else { 3000000 };
5879         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5880         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5881         expect_pending_htlcs_forwardable!(nodes[1]);
5882         check_added_monitors!(nodes[1], 1);
5883
5884         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5885         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5886         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5887         check_added_monitors!(nodes[0], 1);
5888         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5889         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5890         check_added_monitors!(nodes[1], 1);
5891         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5892         check_added_monitors!(nodes[1], 1);
5893         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5894
5895         if check_revoke_no_close {
5896                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5897                 check_added_monitors!(nodes[0], 1);
5898         }
5899
5900         let starting_block = nodes[1].best_block_info();
5901         let mut block = Block {
5902                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5903                 txdata: vec![],
5904         };
5905         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5906                 connect_block(&nodes[0], &block);
5907                 block.header.prev_blockhash = block.block_hash();
5908         }
5909         if !check_revoke_no_close {
5910                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5911                 check_closed_broadcast!(nodes[0], true);
5912                 check_added_monitors!(nodes[0], 1);
5913                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5914         } else {
5915                 let events = nodes[0].node.get_and_clear_pending_events();
5916                 assert_eq!(events.len(), 2);
5917                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
5918                         assert_eq!(*payment_hash, our_payment_hash);
5919                 } else { panic!("Unexpected event"); }
5920                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
5921                         assert_eq!(*payment_hash, our_payment_hash);
5922                 } else { panic!("Unexpected event"); }
5923         }
5924 }
5925
5926 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5927 // There are only a few cases to test here:
5928 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5929 //    broadcastable commitment transactions result in channel closure,
5930 //  * its included in an unrevoked-but-previous remote commitment transaction,
5931 //  * its included in the latest remote or local commitment transactions.
5932 // We test each of the three possible commitment transactions individually and use both dust and
5933 // non-dust HTLCs.
5934 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5935 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5936 // tested for at least one of the cases in other tests.
5937 #[test]
5938 fn htlc_claim_single_commitment_only_a() {
5939         do_htlc_claim_local_commitment_only(true);
5940         do_htlc_claim_local_commitment_only(false);
5941
5942         do_htlc_claim_current_remote_commitment_only(true);
5943         do_htlc_claim_current_remote_commitment_only(false);
5944 }
5945
5946 #[test]
5947 fn htlc_claim_single_commitment_only_b() {
5948         do_htlc_claim_previous_remote_commitment_only(true, false);
5949         do_htlc_claim_previous_remote_commitment_only(false, false);
5950         do_htlc_claim_previous_remote_commitment_only(true, true);
5951         do_htlc_claim_previous_remote_commitment_only(false, true);
5952 }
5953
5954 #[test]
5955 #[should_panic]
5956 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5957         let chanmon_cfgs = create_chanmon_cfgs(2);
5958         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5959         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5960         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5961         // Force duplicate randomness for every get-random call
5962         for node in nodes.iter() {
5963                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5964         }
5965
5966         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5967         let channel_value_satoshis=10000;
5968         let push_msat=10001;
5969         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5970         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5971         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5972         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5973
5974         // Create a second channel with the same random values. This used to panic due to a colliding
5975         // channel_id, but now panics due to a colliding outbound SCID alias.
5976         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5977 }
5978
5979 #[test]
5980 fn bolt2_open_channel_sending_node_checks_part2() {
5981         let chanmon_cfgs = create_chanmon_cfgs(2);
5982         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5983         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5984         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5985
5986         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5987         let channel_value_satoshis=2^24;
5988         let push_msat=10001;
5989         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5990
5991         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5992         let channel_value_satoshis=10000;
5993         // Test when push_msat is equal to 1000 * funding_satoshis.
5994         let push_msat=1000*channel_value_satoshis+1;
5995         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5996
5997         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5998         let channel_value_satoshis=10000;
5999         let push_msat=10001;
6000         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
6001         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6002         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6003
6004         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6005         // 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
6006         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6007
6008         // 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.
6009         assert!(BREAKDOWN_TIMEOUT>0);
6010         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6011
6012         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6013         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6014         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6015
6016         // 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.
6017         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6018         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6019         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6020         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6021         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6022 }
6023
6024 #[test]
6025 fn bolt2_open_channel_sane_dust_limit() {
6026         let chanmon_cfgs = create_chanmon_cfgs(2);
6027         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6028         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6029         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6030
6031         let channel_value_satoshis=1000000;
6032         let push_msat=10001;
6033         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6034         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6035         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6036         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6037
6038         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6039         let events = nodes[1].node.get_and_clear_pending_msg_events();
6040         let err_msg = match events[0] {
6041                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6042                         msg.clone()
6043                 },
6044                 _ => panic!("Unexpected event"),
6045         };
6046         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6047 }
6048
6049 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6050 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6051 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6052 // is no longer affordable once it's freed.
6053 #[test]
6054 fn test_fail_holding_cell_htlc_upon_free() {
6055         let chanmon_cfgs = create_chanmon_cfgs(2);
6056         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6057         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6058         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6059         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6060
6061         // First nodes[0] generates an update_fee, setting the channel's
6062         // pending_update_fee.
6063         {
6064                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6065                 *feerate_lock += 20;
6066         }
6067         nodes[0].node.timer_tick_occurred();
6068         check_added_monitors!(nodes[0], 1);
6069
6070         let events = nodes[0].node.get_and_clear_pending_msg_events();
6071         assert_eq!(events.len(), 1);
6072         let (update_msg, commitment_signed) = match events[0] {
6073                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6074                         (update_fee.as_ref(), commitment_signed)
6075                 },
6076                 _ => panic!("Unexpected event"),
6077         };
6078
6079         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6080
6081         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6082         let channel_reserve = chan_stat.channel_reserve_msat;
6083         let feerate = get_feerate!(nodes[0], chan.2);
6084         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6085
6086         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6087         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6088         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6089
6090         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6091         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6092         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6093         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6094
6095         // Flush the pending fee update.
6096         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6097         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6098         check_added_monitors!(nodes[1], 1);
6099         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6100         check_added_monitors!(nodes[0], 1);
6101
6102         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6103         // HTLC, but now that the fee has been raised the payment will now fail, causing
6104         // us to surface its failure to the user.
6105         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6106         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6107         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);
6108         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 {}",
6109                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6110         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6111
6112         // Check that the payment failed to be sent out.
6113         let events = nodes[0].node.get_and_clear_pending_events();
6114         assert_eq!(events.len(), 1);
6115         match &events[0] {
6116                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, ref short_channel_id, ref error_code, ref error_data, .. } => {
6117                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6118                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6119                         assert_eq!(*rejected_by_dest, false);
6120                         assert_eq!(*all_paths_failed, true);
6121                         assert_eq!(*network_update, None);
6122                         assert_eq!(*short_channel_id, None);
6123                         assert_eq!(*error_code, None);
6124                         assert_eq!(*error_data, None);
6125                 },
6126                 _ => panic!("Unexpected event"),
6127         }
6128 }
6129
6130 // Test that if multiple HTLCs are released from the holding cell and one is
6131 // valid but the other is no longer valid upon release, the valid HTLC can be
6132 // successfully completed while the other one fails as expected.
6133 #[test]
6134 fn test_free_and_fail_holding_cell_htlcs() {
6135         let chanmon_cfgs = create_chanmon_cfgs(2);
6136         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6137         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6138         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6139         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6140
6141         // First nodes[0] generates an update_fee, setting the channel's
6142         // pending_update_fee.
6143         {
6144                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6145                 *feerate_lock += 200;
6146         }
6147         nodes[0].node.timer_tick_occurred();
6148         check_added_monitors!(nodes[0], 1);
6149
6150         let events = nodes[0].node.get_and_clear_pending_msg_events();
6151         assert_eq!(events.len(), 1);
6152         let (update_msg, commitment_signed) = match events[0] {
6153                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6154                         (update_fee.as_ref(), commitment_signed)
6155                 },
6156                 _ => panic!("Unexpected event"),
6157         };
6158
6159         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6160
6161         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6162         let channel_reserve = chan_stat.channel_reserve_msat;
6163         let feerate = get_feerate!(nodes[0], chan.2);
6164         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6165
6166         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6167         let amt_1 = 20000;
6168         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6169         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6170         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6171
6172         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6173         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6174         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6175         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6176         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6177         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6178         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6179
6180         // Flush the pending fee update.
6181         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6182         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6183         check_added_monitors!(nodes[1], 1);
6184         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6185         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6186         check_added_monitors!(nodes[0], 2);
6187
6188         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6189         // but now that the fee has been raised the second payment will now fail, causing us
6190         // to surface its failure to the user. The first payment should succeed.
6191         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6192         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6193         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);
6194         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 {}",
6195                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6196         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6197
6198         // Check that the second payment failed to be sent out.
6199         let events = nodes[0].node.get_and_clear_pending_events();
6200         assert_eq!(events.len(), 1);
6201         match &events[0] {
6202                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, ref short_channel_id, ref error_code, ref error_data, .. } => {
6203                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6204                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6205                         assert_eq!(*rejected_by_dest, false);
6206                         assert_eq!(*all_paths_failed, true);
6207                         assert_eq!(*network_update, None);
6208                         assert_eq!(*short_channel_id, None);
6209                         assert_eq!(*error_code, None);
6210                         assert_eq!(*error_data, None);
6211                 },
6212                 _ => panic!("Unexpected event"),
6213         }
6214
6215         // Complete the first payment and the RAA from the fee update.
6216         let (payment_event, send_raa_event) = {
6217                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6218                 assert_eq!(msgs.len(), 2);
6219                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6220         };
6221         let raa = match send_raa_event {
6222                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6223                 _ => panic!("Unexpected event"),
6224         };
6225         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6226         check_added_monitors!(nodes[1], 1);
6227         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6228         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6229         let events = nodes[1].node.get_and_clear_pending_events();
6230         assert_eq!(events.len(), 1);
6231         match events[0] {
6232                 Event::PendingHTLCsForwardable { .. } => {},
6233                 _ => panic!("Unexpected event"),
6234         }
6235         nodes[1].node.process_pending_htlc_forwards();
6236         let events = nodes[1].node.get_and_clear_pending_events();
6237         assert_eq!(events.len(), 1);
6238         match events[0] {
6239                 Event::PaymentReceived { .. } => {},
6240                 _ => panic!("Unexpected event"),
6241         }
6242         nodes[1].node.claim_funds(payment_preimage_1);
6243         check_added_monitors!(nodes[1], 1);
6244         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6245         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6246         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6247         expect_payment_sent!(nodes[0], payment_preimage_1);
6248 }
6249
6250 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6251 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6252 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6253 // once it's freed.
6254 #[test]
6255 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6256         let chanmon_cfgs = create_chanmon_cfgs(3);
6257         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6258         // When this test was written, the default base fee floated based on the HTLC count.
6259         // It is now fixed, so we simply set the fee to the expected value here.
6260         let mut config = test_default_channel_config();
6261         config.channel_options.forwarding_fee_base_msat = 196;
6262         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6263         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6264         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6265         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6266
6267         // First nodes[1] generates an update_fee, setting the channel's
6268         // pending_update_fee.
6269         {
6270                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6271                 *feerate_lock += 20;
6272         }
6273         nodes[1].node.timer_tick_occurred();
6274         check_added_monitors!(nodes[1], 1);
6275
6276         let events = nodes[1].node.get_and_clear_pending_msg_events();
6277         assert_eq!(events.len(), 1);
6278         let (update_msg, commitment_signed) = match events[0] {
6279                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6280                         (update_fee.as_ref(), commitment_signed)
6281                 },
6282                 _ => panic!("Unexpected event"),
6283         };
6284
6285         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6286
6287         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6288         let channel_reserve = chan_stat.channel_reserve_msat;
6289         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6290         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6291
6292         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6293         let feemsat = 239;
6294         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6295         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6296         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6297         let payment_event = {
6298                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6299                 check_added_monitors!(nodes[0], 1);
6300
6301                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6302                 assert_eq!(events.len(), 1);
6303
6304                 SendEvent::from_event(events.remove(0))
6305         };
6306         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6307         check_added_monitors!(nodes[1], 0);
6308         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6309         expect_pending_htlcs_forwardable!(nodes[1]);
6310
6311         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6312         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6313
6314         // Flush the pending fee update.
6315         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6316         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6317         check_added_monitors!(nodes[2], 1);
6318         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6319         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6320         check_added_monitors!(nodes[1], 2);
6321
6322         // A final RAA message is generated to finalize the fee update.
6323         let events = nodes[1].node.get_and_clear_pending_msg_events();
6324         assert_eq!(events.len(), 1);
6325
6326         let raa_msg = match &events[0] {
6327                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6328                         msg.clone()
6329                 },
6330                 _ => panic!("Unexpected event"),
6331         };
6332
6333         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6334         check_added_monitors!(nodes[2], 1);
6335         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6336
6337         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6338         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6339         assert_eq!(process_htlc_forwards_event.len(), 1);
6340         match &process_htlc_forwards_event[0] {
6341                 &Event::PendingHTLCsForwardable { .. } => {},
6342                 _ => panic!("Unexpected event"),
6343         }
6344
6345         // In response, we call ChannelManager's process_pending_htlc_forwards
6346         nodes[1].node.process_pending_htlc_forwards();
6347         check_added_monitors!(nodes[1], 1);
6348
6349         // This causes the HTLC to be failed backwards.
6350         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6351         assert_eq!(fail_event.len(), 1);
6352         let (fail_msg, commitment_signed) = match &fail_event[0] {
6353                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6354                         assert_eq!(updates.update_add_htlcs.len(), 0);
6355                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6356                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6357                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6358                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6359                 },
6360                 _ => panic!("Unexpected event"),
6361         };
6362
6363         // Pass the failure messages back to nodes[0].
6364         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6365         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6366
6367         // Complete the HTLC failure+removal process.
6368         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6369         check_added_monitors!(nodes[0], 1);
6370         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6371         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6372         check_added_monitors!(nodes[1], 2);
6373         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6374         assert_eq!(final_raa_event.len(), 1);
6375         let raa = match &final_raa_event[0] {
6376                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6377                 _ => panic!("Unexpected event"),
6378         };
6379         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6380         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6381         check_added_monitors!(nodes[0], 1);
6382 }
6383
6384 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6385 // 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.
6386 //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.
6387
6388 #[test]
6389 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6390         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6391         let chanmon_cfgs = create_chanmon_cfgs(2);
6392         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6393         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6394         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6395         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6396
6397         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6398         route.paths[0][0].fee_msat = 100;
6399
6400         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6401                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6402         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6403         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6404 }
6405
6406 #[test]
6407 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6408         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6409         let chanmon_cfgs = create_chanmon_cfgs(2);
6410         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6411         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6412         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6413         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6414
6415         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6416         route.paths[0][0].fee_msat = 0;
6417         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6418                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6419
6420         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6421         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6422 }
6423
6424 #[test]
6425 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6426         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6427         let chanmon_cfgs = create_chanmon_cfgs(2);
6428         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6429         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6430         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6431         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6432
6433         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6434         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6435         check_added_monitors!(nodes[0], 1);
6436         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6437         updates.update_add_htlcs[0].amount_msat = 0;
6438
6439         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6440         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6441         check_closed_broadcast!(nodes[1], true).unwrap();
6442         check_added_monitors!(nodes[1], 1);
6443         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6444 }
6445
6446 #[test]
6447 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6448         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6449         //It is enforced when constructing a route.
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
6456         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6457                 .with_features(InvoiceFeatures::known());
6458         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6459         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6460         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6461                 assert_eq!(err, &"Channel CLTV overflowed?"));
6462 }
6463
6464 #[test]
6465 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6466         //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.
6467         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6468         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6469         let chanmon_cfgs = create_chanmon_cfgs(2);
6470         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6471         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6472         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6473         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6474         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6475
6476         for i in 0..max_accepted_htlcs {
6477                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6478                 let payment_event = {
6479                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6480                         check_added_monitors!(nodes[0], 1);
6481
6482                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6483                         assert_eq!(events.len(), 1);
6484                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6485                                 assert_eq!(htlcs[0].htlc_id, i);
6486                         } else {
6487                                 assert!(false);
6488                         }
6489                         SendEvent::from_event(events.remove(0))
6490                 };
6491                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6492                 check_added_monitors!(nodes[1], 0);
6493                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6494
6495                 expect_pending_htlcs_forwardable!(nodes[1]);
6496                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6497         }
6498         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6499         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6500                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6501
6502         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6503         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6504 }
6505
6506 #[test]
6507 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6508         //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.
6509         let chanmon_cfgs = create_chanmon_cfgs(2);
6510         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6511         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6512         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6513         let channel_value = 100000;
6514         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6515         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6516
6517         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6518
6519         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6520         // Manually create a route over our max in flight (which our router normally automatically
6521         // limits us to.
6522         route.paths[0][0].fee_msat =  max_in_flight + 1;
6523         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6524                 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)));
6525
6526         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6527         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);
6528
6529         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6530 }
6531
6532 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6533 #[test]
6534 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6535         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6536         let chanmon_cfgs = create_chanmon_cfgs(2);
6537         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6538         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6539         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6540         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6541         let htlc_minimum_msat: u64;
6542         {
6543                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6544                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6545                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6546         }
6547
6548         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6549         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6550         check_added_monitors!(nodes[0], 1);
6551         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6552         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6553         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6554         assert!(nodes[1].node.list_channels().is_empty());
6555         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6556         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()));
6557         check_added_monitors!(nodes[1], 1);
6558         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6559 }
6560
6561 #[test]
6562 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6563         //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
6564         let chanmon_cfgs = create_chanmon_cfgs(2);
6565         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6566         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6567         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6568         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6569
6570         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6571         let channel_reserve = chan_stat.channel_reserve_msat;
6572         let feerate = get_feerate!(nodes[0], chan.2);
6573         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6574         // The 2* and +1 are for the fee spike reserve.
6575         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6576
6577         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6578         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6579         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6580         check_added_monitors!(nodes[0], 1);
6581         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6582
6583         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6584         // at this time channel-initiatee receivers are not required to enforce that senders
6585         // respect the fee_spike_reserve.
6586         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6587         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6588
6589         assert!(nodes[1].node.list_channels().is_empty());
6590         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6591         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6592         check_added_monitors!(nodes[1], 1);
6593         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6594 }
6595
6596 #[test]
6597 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6598         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6599         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6600         let chanmon_cfgs = create_chanmon_cfgs(2);
6601         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6602         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6603         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6604         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6605
6606         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6607         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
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
6645         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6646         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6647         check_added_monitors!(nodes[0], 1);
6648         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6649         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6650         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6651
6652         assert!(nodes[1].node.list_channels().is_empty());
6653         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6654         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6655         check_added_monitors!(nodes[1], 1);
6656         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6657 }
6658
6659 #[test]
6660 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6661         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6662         let chanmon_cfgs = create_chanmon_cfgs(2);
6663         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6664         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6665         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6666
6667         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6668         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6669         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6670         check_added_monitors!(nodes[0], 1);
6671         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6672         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6673         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6674
6675         assert!(nodes[1].node.list_channels().is_empty());
6676         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6677         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6678         check_added_monitors!(nodes[1], 1);
6679         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6680 }
6681
6682 #[test]
6683 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6684         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6685         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6686         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6687         let chanmon_cfgs = create_chanmon_cfgs(2);
6688         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6689         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6690         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6691
6692         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6693         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6694         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6695         check_added_monitors!(nodes[0], 1);
6696         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6697         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6698
6699         //Disconnect and Reconnect
6700         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6701         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6702         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6703         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6704         assert_eq!(reestablish_1.len(), 1);
6705         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6706         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6707         assert_eq!(reestablish_2.len(), 1);
6708         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6709         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6710         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6711         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6712
6713         //Resend HTLC
6714         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6715         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6716         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6717         check_added_monitors!(nodes[1], 1);
6718         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6719
6720         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6721
6722         assert!(nodes[1].node.list_channels().is_empty());
6723         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6724         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6725         check_added_monitors!(nodes[1], 1);
6726         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6727 }
6728
6729 #[test]
6730 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6731         //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.
6732
6733         let chanmon_cfgs = create_chanmon_cfgs(2);
6734         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6735         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6736         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6737         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6738         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6739         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6740
6741         check_added_monitors!(nodes[0], 1);
6742         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6743         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6744
6745         let update_msg = msgs::UpdateFulfillHTLC{
6746                 channel_id: chan.2,
6747                 htlc_id: 0,
6748                 payment_preimage: our_payment_preimage,
6749         };
6750
6751         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6752
6753         assert!(nodes[0].node.list_channels().is_empty());
6754         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6755         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()));
6756         check_added_monitors!(nodes[0], 1);
6757         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6758 }
6759
6760 #[test]
6761 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6762         //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.
6763
6764         let chanmon_cfgs = create_chanmon_cfgs(2);
6765         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6766         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6767         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6768         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6769
6770         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6771         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6772         check_added_monitors!(nodes[0], 1);
6773         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6774         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6775
6776         let update_msg = msgs::UpdateFailHTLC{
6777                 channel_id: chan.2,
6778                 htlc_id: 0,
6779                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6780         };
6781
6782         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6783
6784         assert!(nodes[0].node.list_channels().is_empty());
6785         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6786         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()));
6787         check_added_monitors!(nodes[0], 1);
6788         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6789 }
6790
6791 #[test]
6792 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6793         //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.
6794
6795         let chanmon_cfgs = create_chanmon_cfgs(2);
6796         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6797         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6798         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6799         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6800
6801         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6802         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6803         check_added_monitors!(nodes[0], 1);
6804         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6805         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6806         let update_msg = msgs::UpdateFailMalformedHTLC{
6807                 channel_id: chan.2,
6808                 htlc_id: 0,
6809                 sha256_of_onion: [1; 32],
6810                 failure_code: 0x8000,
6811         };
6812
6813         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6814
6815         assert!(nodes[0].node.list_channels().is_empty());
6816         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6817         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()));
6818         check_added_monitors!(nodes[0], 1);
6819         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6820 }
6821
6822 #[test]
6823 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6824         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6825
6826         let chanmon_cfgs = create_chanmon_cfgs(2);
6827         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6828         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6829         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6830         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6831
6832         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6833
6834         nodes[1].node.claim_funds(our_payment_preimage);
6835         check_added_monitors!(nodes[1], 1);
6836
6837         let events = nodes[1].node.get_and_clear_pending_msg_events();
6838         assert_eq!(events.len(), 1);
6839         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6840                 match events[0] {
6841                         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, .. } } => {
6842                                 assert!(update_add_htlcs.is_empty());
6843                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6844                                 assert!(update_fail_htlcs.is_empty());
6845                                 assert!(update_fail_malformed_htlcs.is_empty());
6846                                 assert!(update_fee.is_none());
6847                                 update_fulfill_htlcs[0].clone()
6848                         },
6849                         _ => panic!("Unexpected event"),
6850                 }
6851         };
6852
6853         update_fulfill_msg.htlc_id = 1;
6854
6855         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6856
6857         assert!(nodes[0].node.list_channels().is_empty());
6858         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6859         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6860         check_added_monitors!(nodes[0], 1);
6861         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6862 }
6863
6864 #[test]
6865 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6866         //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.
6867
6868         let chanmon_cfgs = create_chanmon_cfgs(2);
6869         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6870         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6871         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6872         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6873
6874         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6875
6876         nodes[1].node.claim_funds(our_payment_preimage);
6877         check_added_monitors!(nodes[1], 1);
6878
6879         let events = nodes[1].node.get_and_clear_pending_msg_events();
6880         assert_eq!(events.len(), 1);
6881         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6882                 match events[0] {
6883                         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, .. } } => {
6884                                 assert!(update_add_htlcs.is_empty());
6885                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6886                                 assert!(update_fail_htlcs.is_empty());
6887                                 assert!(update_fail_malformed_htlcs.is_empty());
6888                                 assert!(update_fee.is_none());
6889                                 update_fulfill_htlcs[0].clone()
6890                         },
6891                         _ => panic!("Unexpected event"),
6892                 }
6893         };
6894
6895         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6896
6897         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6898
6899         assert!(nodes[0].node.list_channels().is_empty());
6900         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6901         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6902         check_added_monitors!(nodes[0], 1);
6903         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6904 }
6905
6906 #[test]
6907 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6908         //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.
6909
6910         let chanmon_cfgs = create_chanmon_cfgs(2);
6911         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6912         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6913         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6914         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6915
6916         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6917         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6918         check_added_monitors!(nodes[0], 1);
6919
6920         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6921         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6922
6923         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6924         check_added_monitors!(nodes[1], 0);
6925         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6926
6927         let events = nodes[1].node.get_and_clear_pending_msg_events();
6928
6929         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6930                 match events[0] {
6931                         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, .. } } => {
6932                                 assert!(update_add_htlcs.is_empty());
6933                                 assert!(update_fulfill_htlcs.is_empty());
6934                                 assert!(update_fail_htlcs.is_empty());
6935                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6936                                 assert!(update_fee.is_none());
6937                                 update_fail_malformed_htlcs[0].clone()
6938                         },
6939                         _ => panic!("Unexpected event"),
6940                 }
6941         };
6942         update_msg.failure_code &= !0x8000;
6943         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6944
6945         assert!(nodes[0].node.list_channels().is_empty());
6946         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6947         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6948         check_added_monitors!(nodes[0], 1);
6949         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6950 }
6951
6952 #[test]
6953 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6954         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6955         //    * 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.
6956
6957         let chanmon_cfgs = create_chanmon_cfgs(3);
6958         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6959         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6960         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6961         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6962         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6963
6964         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6965
6966         //First hop
6967         let mut payment_event = {
6968                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6969                 check_added_monitors!(nodes[0], 1);
6970                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6971                 assert_eq!(events.len(), 1);
6972                 SendEvent::from_event(events.remove(0))
6973         };
6974         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6975         check_added_monitors!(nodes[1], 0);
6976         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6977         expect_pending_htlcs_forwardable!(nodes[1]);
6978         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6979         assert_eq!(events_2.len(), 1);
6980         check_added_monitors!(nodes[1], 1);
6981         payment_event = SendEvent::from_event(events_2.remove(0));
6982         assert_eq!(payment_event.msgs.len(), 1);
6983
6984         //Second Hop
6985         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6986         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6987         check_added_monitors!(nodes[2], 0);
6988         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6989
6990         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6991         assert_eq!(events_3.len(), 1);
6992         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6993                 match events_3[0] {
6994                         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 } } => {
6995                                 assert!(update_add_htlcs.is_empty());
6996                                 assert!(update_fulfill_htlcs.is_empty());
6997                                 assert!(update_fail_htlcs.is_empty());
6998                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6999                                 assert!(update_fee.is_none());
7000                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7001                         },
7002                         _ => panic!("Unexpected event"),
7003                 }
7004         };
7005
7006         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7007
7008         check_added_monitors!(nodes[1], 0);
7009         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7010         expect_pending_htlcs_forwardable!(nodes[1]);
7011         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7012         assert_eq!(events_4.len(), 1);
7013
7014         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7015         match events_4[0] {
7016                 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, .. } } => {
7017                         assert!(update_add_htlcs.is_empty());
7018                         assert!(update_fulfill_htlcs.is_empty());
7019                         assert_eq!(update_fail_htlcs.len(), 1);
7020                         assert!(update_fail_malformed_htlcs.is_empty());
7021                         assert!(update_fee.is_none());
7022                 },
7023                 _ => panic!("Unexpected event"),
7024         };
7025
7026         check_added_monitors!(nodes[1], 1);
7027 }
7028
7029 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7030         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7031         // 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
7032         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7033
7034         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7035         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7036         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7037         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7038         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7039         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7040
7041         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7042
7043         // We route 2 dust-HTLCs between A and B
7044         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7045         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7046         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7047
7048         // Cache one local commitment tx as previous
7049         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7050
7051         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7052         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7053         check_added_monitors!(nodes[1], 0);
7054         expect_pending_htlcs_forwardable!(nodes[1]);
7055         check_added_monitors!(nodes[1], 1);
7056
7057         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7058         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7059         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7060         check_added_monitors!(nodes[0], 1);
7061
7062         // Cache one local commitment tx as lastest
7063         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7064
7065         let events = nodes[0].node.get_and_clear_pending_msg_events();
7066         match events[0] {
7067                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7068                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7069                 },
7070                 _ => panic!("Unexpected event"),
7071         }
7072         match events[1] {
7073                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7074                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7075                 },
7076                 _ => panic!("Unexpected event"),
7077         }
7078
7079         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7080         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7081         if announce_latest {
7082                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7083         } else {
7084                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7085         }
7086
7087         check_closed_broadcast!(nodes[0], true);
7088         check_added_monitors!(nodes[0], 1);
7089         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7090
7091         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7092         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7093         let events = nodes[0].node.get_and_clear_pending_events();
7094         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7095         assert_eq!(events.len(), 2);
7096         let mut first_failed = false;
7097         for event in events {
7098                 match event {
7099                         Event::PaymentPathFailed { payment_hash, .. } => {
7100                                 if payment_hash == payment_hash_1 {
7101                                         assert!(!first_failed);
7102                                         first_failed = true;
7103                                 } else {
7104                                         assert_eq!(payment_hash, payment_hash_2);
7105                                 }
7106                         }
7107                         _ => panic!("Unexpected event"),
7108                 }
7109         }
7110 }
7111
7112 #[test]
7113 fn test_failure_delay_dust_htlc_local_commitment() {
7114         do_test_failure_delay_dust_htlc_local_commitment(true);
7115         do_test_failure_delay_dust_htlc_local_commitment(false);
7116 }
7117
7118 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7119         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7120         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7121         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7122         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7123         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7124         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7125
7126         let chanmon_cfgs = create_chanmon_cfgs(3);
7127         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7128         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7129         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7130         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7131
7132         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7133
7134         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7135         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7136
7137         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7138         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7139
7140         // We revoked bs_commitment_tx
7141         if revoked {
7142                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7143                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7144         }
7145
7146         let mut timeout_tx = Vec::new();
7147         if local {
7148                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7149                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7150                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7151                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7152                 expect_payment_failed!(nodes[0], dust_hash, true);
7153
7154                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7155                 check_closed_broadcast!(nodes[0], true);
7156                 check_added_monitors!(nodes[0], 1);
7157                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7158                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7159                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7160                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7161                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7162                 mine_transaction(&nodes[0], &timeout_tx[0]);
7163                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7164                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7165         } else {
7166                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7167                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7168                 check_closed_broadcast!(nodes[0], true);
7169                 check_added_monitors!(nodes[0], 1);
7170                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7171                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7172                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7173                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7174                 if !revoked {
7175                         expect_payment_failed!(nodes[0], dust_hash, true);
7176                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7177                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7178                         mine_transaction(&nodes[0], &timeout_tx[0]);
7179                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7180                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7181                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7182                 } else {
7183                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7184                         // commitment tx
7185                         let events = nodes[0].node.get_and_clear_pending_events();
7186                         assert_eq!(events.len(), 2);
7187                         let first;
7188                         match events[0] {
7189                                 Event::PaymentPathFailed { payment_hash, .. } => {
7190                                         if payment_hash == dust_hash { first = true; }
7191                                         else { first = false; }
7192                                 },
7193                                 _ => panic!("Unexpected event"),
7194                         }
7195                         match events[1] {
7196                                 Event::PaymentPathFailed { payment_hash, .. } => {
7197                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7198                                         else { assert_eq!(payment_hash, dust_hash); }
7199                                 },
7200                                 _ => panic!("Unexpected event"),
7201                         }
7202                 }
7203         }
7204 }
7205
7206 #[test]
7207 fn test_sweep_outbound_htlc_failure_update() {
7208         do_test_sweep_outbound_htlc_failure_update(false, true);
7209         do_test_sweep_outbound_htlc_failure_update(false, false);
7210         do_test_sweep_outbound_htlc_failure_update(true, false);
7211 }
7212
7213 #[test]
7214 fn test_user_configurable_csv_delay() {
7215         // We test our channel constructors yield errors when we pass them absurd csv delay
7216
7217         let mut low_our_to_self_config = UserConfig::default();
7218         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7219         let mut high_their_to_self_config = UserConfig::default();
7220         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7221         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7222         let chanmon_cfgs = create_chanmon_cfgs(2);
7223         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7224         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7225         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7226
7227         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7228         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7229                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7230                 &low_our_to_self_config, 0, 42)
7231         {
7232                 match error {
7233                         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())); },
7234                         _ => panic!("Unexpected event"),
7235                 }
7236         } else { assert!(false) }
7237
7238         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7239         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7240         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7241         open_channel.to_self_delay = 200;
7242         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7243                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7244                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7245         {
7246                 match error {
7247                         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()));  },
7248                         _ => panic!("Unexpected event"),
7249                 }
7250         } else { assert!(false); }
7251
7252         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7253         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7254         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()));
7255         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7256         accept_channel.to_self_delay = 200;
7257         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7258         let reason_msg;
7259         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7260                 match action {
7261                         &ErrorAction::SendErrorMessage { ref msg } => {
7262                                 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()));
7263                                 reason_msg = msg.data.clone();
7264                         },
7265                         _ => { panic!(); }
7266                 }
7267         } else { panic!(); }
7268         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7269
7270         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7271         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7272         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7273         open_channel.to_self_delay = 200;
7274         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7275                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7276                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7277         {
7278                 match error {
7279                         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())); },
7280                         _ => panic!("Unexpected event"),
7281                 }
7282         } else { assert!(false); }
7283 }
7284
7285 #[test]
7286 fn test_data_loss_protect() {
7287         // We want to be sure that :
7288         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7289         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7290         // * we close channel in case of detecting other being fallen behind
7291         // * we are able to claim our own outputs thanks to to_remote being static
7292         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7293         let persister;
7294         let logger;
7295         let fee_estimator;
7296         let tx_broadcaster;
7297         let chain_source;
7298         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7299         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7300         // during signing due to revoked tx
7301         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7302         let keys_manager = &chanmon_cfgs[0].keys_manager;
7303         let monitor;
7304         let node_state_0;
7305         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7306         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7307         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7308
7309         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7310
7311         // Cache node A state before any channel update
7312         let previous_node_state = nodes[0].node.encode();
7313         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7314         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7315
7316         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7317         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7318
7319         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7320         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7321
7322         // Restore node A from previous state
7323         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7324         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7325         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7326         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7327         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7328         persister = test_utils::TestPersister::new();
7329         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7330         node_state_0 = {
7331                 let mut channel_monitors = HashMap::new();
7332                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7333                 <(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 {
7334                         keys_manager: keys_manager,
7335                         fee_estimator: &fee_estimator,
7336                         chain_monitor: &monitor,
7337                         logger: &logger,
7338                         tx_broadcaster: &tx_broadcaster,
7339                         default_config: UserConfig::default(),
7340                         channel_monitors,
7341                 }).unwrap().1
7342         };
7343         nodes[0].node = &node_state_0;
7344         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7345         nodes[0].chain_monitor = &monitor;
7346         nodes[0].chain_source = &chain_source;
7347
7348         check_added_monitors!(nodes[0], 1);
7349
7350         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7351         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7352
7353         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7354
7355         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7356         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7357         check_added_monitors!(nodes[0], 1);
7358
7359         {
7360                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7361                 assert_eq!(node_txn.len(), 0);
7362         }
7363
7364         let mut reestablish_1 = Vec::with_capacity(1);
7365         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7366                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7367                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7368                         reestablish_1.push(msg.clone());
7369                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7370                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7371                         match action {
7372                                 &ErrorAction::SendErrorMessage { ref msg } => {
7373                                         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");
7374                                 },
7375                                 _ => panic!("Unexpected event!"),
7376                         }
7377                 } else {
7378                         panic!("Unexpected event")
7379                 }
7380         }
7381
7382         // Check we close channel detecting A is fallen-behind
7383         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7384         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7385         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7386         check_added_monitors!(nodes[1], 1);
7387
7388         // Check A is able to claim to_remote output
7389         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7390         assert_eq!(node_txn.len(), 1);
7391         check_spends!(node_txn[0], chan.3);
7392         assert_eq!(node_txn[0].output.len(), 2);
7393         mine_transaction(&nodes[0], &node_txn[0]);
7394         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7395         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() });
7396         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7397         assert_eq!(spend_txn.len(), 1);
7398         check_spends!(spend_txn[0], node_txn[0]);
7399 }
7400
7401 #[test]
7402 fn test_check_htlc_underpaying() {
7403         // Send payment through A -> B but A is maliciously
7404         // sending a probe payment (i.e less than expected value0
7405         // to B, B should refuse payment.
7406
7407         let chanmon_cfgs = create_chanmon_cfgs(2);
7408         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7409         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7410         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7411
7412         // Create some initial channels
7413         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7414
7415         let scorer = test_utils::TestScorer::with_penalty(0);
7416         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7417         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7418         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None, 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7419         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7420         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7421         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7422         check_added_monitors!(nodes[0], 1);
7423
7424         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7425         assert_eq!(events.len(), 1);
7426         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7427         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7428         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7429
7430         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7431         // and then will wait a second random delay before failing the HTLC back:
7432         expect_pending_htlcs_forwardable!(nodes[1]);
7433         expect_pending_htlcs_forwardable!(nodes[1]);
7434
7435         // Node 3 is expecting payment of 100_000 but received 10_000,
7436         // it should fail htlc like we didn't know the preimage.
7437         nodes[1].node.process_pending_htlc_forwards();
7438
7439         let events = nodes[1].node.get_and_clear_pending_msg_events();
7440         assert_eq!(events.len(), 1);
7441         let (update_fail_htlc, commitment_signed) = match events[0] {
7442                 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 } } => {
7443                         assert!(update_add_htlcs.is_empty());
7444                         assert!(update_fulfill_htlcs.is_empty());
7445                         assert_eq!(update_fail_htlcs.len(), 1);
7446                         assert!(update_fail_malformed_htlcs.is_empty());
7447                         assert!(update_fee.is_none());
7448                         (update_fail_htlcs[0].clone(), commitment_signed)
7449                 },
7450                 _ => panic!("Unexpected event"),
7451         };
7452         check_added_monitors!(nodes[1], 1);
7453
7454         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7455         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7456
7457         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7458         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7459         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7460         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7461 }
7462
7463 #[test]
7464 fn test_announce_disable_channels() {
7465         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7466         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7467
7468         let chanmon_cfgs = create_chanmon_cfgs(2);
7469         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7470         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7471         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7472
7473         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7474         create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7475         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7476
7477         // Disconnect peers
7478         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7479         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7480
7481         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7482         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7483         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7484         assert_eq!(msg_events.len(), 3);
7485         let mut chans_disabled = HashMap::new();
7486         for e in msg_events {
7487                 match e {
7488                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7489                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7490                                 // Check that each channel gets updated exactly once
7491                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7492                                         panic!("Generated ChannelUpdate for wrong chan!");
7493                                 }
7494                         },
7495                         _ => panic!("Unexpected event"),
7496                 }
7497         }
7498         // Reconnect peers
7499         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7500         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7501         assert_eq!(reestablish_1.len(), 3);
7502         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7503         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7504         assert_eq!(reestablish_2.len(), 3);
7505
7506         // Reestablish chan_1
7507         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7508         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7509         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7510         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7511         // Reestablish chan_2
7512         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7513         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7514         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7515         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7516         // Reestablish chan_3
7517         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7518         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7519         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7520         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7521
7522         nodes[0].node.timer_tick_occurred();
7523         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7524         nodes[0].node.timer_tick_occurred();
7525         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7526         assert_eq!(msg_events.len(), 3);
7527         for e in msg_events {
7528                 match e {
7529                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7530                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7531                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7532                                         // Each update should have a higher timestamp than the previous one, replacing
7533                                         // the old one.
7534                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7535                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7536                                 }
7537                         },
7538                         _ => panic!("Unexpected event"),
7539                 }
7540         }
7541         // Check that each channel gets updated exactly once
7542         assert!(chans_disabled.is_empty());
7543 }
7544
7545 #[test]
7546 fn test_bump_penalty_txn_on_revoked_commitment() {
7547         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7548         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7549
7550         let chanmon_cfgs = create_chanmon_cfgs(2);
7551         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7552         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7553         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7554
7555         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7556
7557         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7558         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7559                 .with_features(InvoiceFeatures::known());
7560         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7561         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7562
7563         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7564         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7565         assert_eq!(revoked_txn[0].output.len(), 4);
7566         assert_eq!(revoked_txn[0].input.len(), 1);
7567         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7568         let revoked_txid = revoked_txn[0].txid();
7569
7570         let mut penalty_sum = 0;
7571         for outp in revoked_txn[0].output.iter() {
7572                 if outp.script_pubkey.is_v0_p2wsh() {
7573                         penalty_sum += outp.value;
7574                 }
7575         }
7576
7577         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7578         let header_114 = connect_blocks(&nodes[1], 14);
7579
7580         // Actually revoke tx by claiming a HTLC
7581         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7582         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7583         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7584         check_added_monitors!(nodes[1], 1);
7585
7586         // One or more justice tx should have been broadcast, check it
7587         let penalty_1;
7588         let feerate_1;
7589         {
7590                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7591                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7592                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7593                 assert_eq!(node_txn[0].output.len(), 1);
7594                 check_spends!(node_txn[0], revoked_txn[0]);
7595                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7596                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7597                 penalty_1 = node_txn[0].txid();
7598                 node_txn.clear();
7599         };
7600
7601         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7602         connect_blocks(&nodes[1], 15);
7603         let mut penalty_2 = penalty_1;
7604         let mut feerate_2 = 0;
7605         {
7606                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7607                 assert_eq!(node_txn.len(), 1);
7608                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7609                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7610                         assert_eq!(node_txn[0].output.len(), 1);
7611                         check_spends!(node_txn[0], revoked_txn[0]);
7612                         penalty_2 = node_txn[0].txid();
7613                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7614                         assert_ne!(penalty_2, penalty_1);
7615                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7616                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7617                         // Verify 25% bump heuristic
7618                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7619                         node_txn.clear();
7620                 }
7621         }
7622         assert_ne!(feerate_2, 0);
7623
7624         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7625         connect_blocks(&nodes[1], 1);
7626         let penalty_3;
7627         let mut feerate_3 = 0;
7628         {
7629                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7630                 assert_eq!(node_txn.len(), 1);
7631                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7632                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7633                         assert_eq!(node_txn[0].output.len(), 1);
7634                         check_spends!(node_txn[0], revoked_txn[0]);
7635                         penalty_3 = node_txn[0].txid();
7636                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7637                         assert_ne!(penalty_3, penalty_2);
7638                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7639                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7640                         // Verify 25% bump heuristic
7641                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7642                         node_txn.clear();
7643                 }
7644         }
7645         assert_ne!(feerate_3, 0);
7646
7647         nodes[1].node.get_and_clear_pending_events();
7648         nodes[1].node.get_and_clear_pending_msg_events();
7649 }
7650
7651 #[test]
7652 fn test_bump_penalty_txn_on_revoked_htlcs() {
7653         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7654         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7655
7656         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7657         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7658         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7659         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7660         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7661
7662         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7663         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7664         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7665         let scorer = test_utils::TestScorer::with_penalty(0);
7666         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7667         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7668                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7669         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7670         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7671         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7672                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7673         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7674
7675         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7676         assert_eq!(revoked_local_txn[0].input.len(), 1);
7677         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7678
7679         // Revoke local commitment tx
7680         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7681
7682         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7683         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7684         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7685         check_closed_broadcast!(nodes[1], true);
7686         check_added_monitors!(nodes[1], 1);
7687         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7688         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7689
7690         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7691         assert_eq!(revoked_htlc_txn.len(), 3);
7692         check_spends!(revoked_htlc_txn[1], chan.3);
7693
7694         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7695         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7696         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7697
7698         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7699         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7700         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7701         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7702
7703         // Broadcast set of revoked txn on A
7704         let hash_128 = connect_blocks(&nodes[0], 40);
7705         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7706         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7707         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7708         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7709         let events = nodes[0].node.get_and_clear_pending_events();
7710         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7711         match events[1] {
7712                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7713                 _ => panic!("Unexpected event"),
7714         }
7715         let first;
7716         let feerate_1;
7717         let penalty_txn;
7718         {
7719                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7720                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7721                 // Verify claim tx are spending revoked HTLC txn
7722
7723                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7724                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7725                 // which are included in the same block (they are broadcasted because we scan the
7726                 // transactions linearly and generate claims as we go, they likely should be removed in the
7727                 // future).
7728                 assert_eq!(node_txn[0].input.len(), 1);
7729                 check_spends!(node_txn[0], revoked_local_txn[0]);
7730                 assert_eq!(node_txn[1].input.len(), 1);
7731                 check_spends!(node_txn[1], revoked_local_txn[0]);
7732                 assert_eq!(node_txn[2].input.len(), 1);
7733                 check_spends!(node_txn[2], revoked_local_txn[0]);
7734
7735                 // Each of the three justice transactions claim a separate (single) output of the three
7736                 // available, which we check here:
7737                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7738                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7739                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7740
7741                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7742                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7743
7744                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7745                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7746                 // a remote commitment tx has already been confirmed).
7747                 check_spends!(node_txn[3], chan.3);
7748
7749                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7750                 // output, checked above).
7751                 assert_eq!(node_txn[4].input.len(), 2);
7752                 assert_eq!(node_txn[4].output.len(), 1);
7753                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7754
7755                 first = node_txn[4].txid();
7756                 // Store both feerates for later comparison
7757                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7758                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7759                 penalty_txn = vec![node_txn[2].clone()];
7760                 node_txn.clear();
7761         }
7762
7763         // Connect one more block to see if bumped penalty are issued for HTLC txn
7764         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7765         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7766         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7767         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7768         {
7769                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7770                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7771
7772                 check_spends!(node_txn[0], revoked_local_txn[0]);
7773                 check_spends!(node_txn[1], revoked_local_txn[0]);
7774                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7775                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7776                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7777                 } else {
7778                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7779                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7780                 }
7781
7782                 node_txn.clear();
7783         };
7784
7785         // Few more blocks to confirm penalty txn
7786         connect_blocks(&nodes[0], 4);
7787         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7788         let header_144 = connect_blocks(&nodes[0], 9);
7789         let node_txn = {
7790                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7791                 assert_eq!(node_txn.len(), 1);
7792
7793                 assert_eq!(node_txn[0].input.len(), 2);
7794                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7795                 // Verify bumped tx is different and 25% bump heuristic
7796                 assert_ne!(first, node_txn[0].txid());
7797                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7798                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7799                 assert!(feerate_2 * 100 > feerate_1 * 125);
7800                 let txn = vec![node_txn[0].clone()];
7801                 node_txn.clear();
7802                 txn
7803         };
7804         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7805         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7806         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7807         connect_blocks(&nodes[0], 20);
7808         {
7809                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7810                 // We verify than no new transaction has been broadcast because previously
7811                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7812                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7813                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7814                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7815                 // up bumped justice generation.
7816                 assert_eq!(node_txn.len(), 0);
7817                 node_txn.clear();
7818         }
7819         check_closed_broadcast!(nodes[0], true);
7820         check_added_monitors!(nodes[0], 1);
7821 }
7822
7823 #[test]
7824 fn test_bump_penalty_txn_on_remote_commitment() {
7825         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7826         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7827
7828         // Create 2 HTLCs
7829         // Provide preimage for one
7830         // Check aggregation
7831
7832         let chanmon_cfgs = create_chanmon_cfgs(2);
7833         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7834         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7835         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7836
7837         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7838         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7839         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7840
7841         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7842         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7843         assert_eq!(remote_txn[0].output.len(), 4);
7844         assert_eq!(remote_txn[0].input.len(), 1);
7845         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7846
7847         // Claim a HTLC without revocation (provide B monitor with preimage)
7848         nodes[1].node.claim_funds(payment_preimage);
7849         mine_transaction(&nodes[1], &remote_txn[0]);
7850         check_added_monitors!(nodes[1], 2);
7851         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7852
7853         // One or more claim tx should have been broadcast, check it
7854         let timeout;
7855         let preimage;
7856         let preimage_bump;
7857         let feerate_timeout;
7858         let feerate_preimage;
7859         {
7860                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7861                 // 9 transactions including:
7862                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7863                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7864                 // 2 * HTLC-Success (one RBF bump we'll check later)
7865                 // 1 * HTLC-Timeout
7866                 assert_eq!(node_txn.len(), 8);
7867                 assert_eq!(node_txn[0].input.len(), 1);
7868                 assert_eq!(node_txn[6].input.len(), 1);
7869                 check_spends!(node_txn[0], remote_txn[0]);
7870                 check_spends!(node_txn[6], remote_txn[0]);
7871                 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7872                 preimage_bump = node_txn[3].clone();
7873
7874                 check_spends!(node_txn[1], chan.3);
7875                 check_spends!(node_txn[2], node_txn[1]);
7876                 assert_eq!(node_txn[1], node_txn[4]);
7877                 assert_eq!(node_txn[2], node_txn[5]);
7878
7879                 timeout = node_txn[6].txid();
7880                 let index = node_txn[6].input[0].previous_output.vout;
7881                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7882                 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7883
7884                 preimage = node_txn[0].txid();
7885                 let index = node_txn[0].input[0].previous_output.vout;
7886                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7887                 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7888
7889                 node_txn.clear();
7890         };
7891         assert_ne!(feerate_timeout, 0);
7892         assert_ne!(feerate_preimage, 0);
7893
7894         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7895         connect_blocks(&nodes[1], 15);
7896         {
7897                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7898                 assert_eq!(node_txn.len(), 1);
7899                 assert_eq!(node_txn[0].input.len(), 1);
7900                 assert_eq!(preimage_bump.input.len(), 1);
7901                 check_spends!(node_txn[0], remote_txn[0]);
7902                 check_spends!(preimage_bump, remote_txn[0]);
7903
7904                 let index = preimage_bump.input[0].previous_output.vout;
7905                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7906                 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7907                 assert!(new_feerate * 100 > feerate_timeout * 125);
7908                 assert_ne!(timeout, preimage_bump.txid());
7909
7910                 let index = node_txn[0].input[0].previous_output.vout;
7911                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7912                 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7913                 assert!(new_feerate * 100 > feerate_preimage * 125);
7914                 assert_ne!(preimage, node_txn[0].txid());
7915
7916                 node_txn.clear();
7917         }
7918
7919         nodes[1].node.get_and_clear_pending_events();
7920         nodes[1].node.get_and_clear_pending_msg_events();
7921 }
7922
7923 #[test]
7924 fn test_counterparty_raa_skip_no_crash() {
7925         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7926         // commitment transaction, we would have happily carried on and provided them the next
7927         // commitment transaction based on one RAA forward. This would probably eventually have led to
7928         // channel closure, but it would not have resulted in funds loss. Still, our
7929         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7930         // check simply that the channel is closed in response to such an RAA, but don't check whether
7931         // we decide to punish our counterparty for revoking their funds (as we don't currently
7932         // implement that).
7933         let chanmon_cfgs = create_chanmon_cfgs(2);
7934         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7935         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7936         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7937         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7938
7939         let mut guard = nodes[0].node.channel_state.lock().unwrap();
7940         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7941
7942         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7943
7944         // Make signer believe we got a counterparty signature, so that it allows the revocation
7945         keys.get_enforcement_state().last_holder_commitment -= 1;
7946         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7947
7948         // Must revoke without gaps
7949         keys.get_enforcement_state().last_holder_commitment -= 1;
7950         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7951
7952         keys.get_enforcement_state().last_holder_commitment -= 1;
7953         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7954                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7955
7956         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7957                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7958         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7959         check_added_monitors!(nodes[1], 1);
7960         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7961 }
7962
7963 #[test]
7964 fn test_bump_txn_sanitize_tracking_maps() {
7965         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7966         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7967
7968         let chanmon_cfgs = create_chanmon_cfgs(2);
7969         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7970         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7971         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7972
7973         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7974         // Lock HTLC in both directions
7975         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7976         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7977
7978         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7979         assert_eq!(revoked_local_txn[0].input.len(), 1);
7980         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7981
7982         // Revoke local commitment tx
7983         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7984
7985         // Broadcast set of revoked txn on A
7986         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7987         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7988         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7989
7990         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7991         check_closed_broadcast!(nodes[0], true);
7992         check_added_monitors!(nodes[0], 1);
7993         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7994         let penalty_txn = {
7995                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7996                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7997                 check_spends!(node_txn[0], revoked_local_txn[0]);
7998                 check_spends!(node_txn[1], revoked_local_txn[0]);
7999                 check_spends!(node_txn[2], revoked_local_txn[0]);
8000                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8001                 node_txn.clear();
8002                 penalty_txn
8003         };
8004         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8005         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8006         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8007         {
8008                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8009                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8010                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8011         }
8012 }
8013
8014 #[test]
8015 fn test_pending_claimed_htlc_no_balance_underflow() {
8016         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8017         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8018         let chanmon_cfgs = create_chanmon_cfgs(2);
8019         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8020         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8021         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8022         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8023
8024         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1_010_000).0;
8025         nodes[1].node.claim_funds(payment_preimage);
8026         check_added_monitors!(nodes[1], 1);
8027         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8028
8029         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8030         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8031         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8032         check_added_monitors!(nodes[0], 1);
8033         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8034
8035         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8036         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8037         // can get our balance.
8038
8039         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8040         // the public key of the only hop. This works around ChannelDetails not showing the
8041         // almost-claimed HTLC as available balance.
8042         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8043         route.payment_params = None; // This is all wrong, but unnecessary
8044         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8045         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8046         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8047
8048         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8049 }
8050
8051 #[test]
8052 fn test_channel_conf_timeout() {
8053         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8054         // confirm within 2016 blocks, as recommended by BOLT 2.
8055         let chanmon_cfgs = create_chanmon_cfgs(2);
8056         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8057         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8058         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8059
8060         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8061
8062         // The outbound node should wait forever for confirmation:
8063         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8064         // copied here instead of directly referencing the constant.
8065         connect_blocks(&nodes[0], 2016);
8066         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8067
8068         // The inbound node should fail the channel after exactly 2016 blocks
8069         connect_blocks(&nodes[1], 2015);
8070         check_added_monitors!(nodes[1], 0);
8071         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8072
8073         connect_blocks(&nodes[1], 1);
8074         check_added_monitors!(nodes[1], 1);
8075         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8076         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8077         assert_eq!(close_ev.len(), 1);
8078         match close_ev[0] {
8079                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8080                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8081                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8082                 },
8083                 _ => panic!("Unexpected event"),
8084         }
8085 }
8086
8087 #[test]
8088 fn test_override_channel_config() {
8089         let chanmon_cfgs = create_chanmon_cfgs(2);
8090         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8091         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8092         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8093
8094         // Node0 initiates a channel to node1 using the override config.
8095         let mut override_config = UserConfig::default();
8096         override_config.own_channel_config.our_to_self_delay = 200;
8097
8098         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8099
8100         // Assert the channel created by node0 is using the override config.
8101         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8102         assert_eq!(res.channel_flags, 0);
8103         assert_eq!(res.to_self_delay, 200);
8104 }
8105
8106 #[test]
8107 fn test_override_0msat_htlc_minimum() {
8108         let mut zero_config = UserConfig::default();
8109         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8110         let chanmon_cfgs = create_chanmon_cfgs(2);
8111         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8112         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8113         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8114
8115         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8116         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8117         assert_eq!(res.htlc_minimum_msat, 1);
8118
8119         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8120         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8121         assert_eq!(res.htlc_minimum_msat, 1);
8122 }
8123
8124 #[test]
8125 fn test_manually_accept_inbound_channel_request() {
8126         let mut manually_accept_conf = UserConfig::default();
8127         manually_accept_conf.manually_accept_inbound_channels = true;
8128         let chanmon_cfgs = create_chanmon_cfgs(2);
8129         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8130         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8131         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8132
8133         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8134         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8135
8136         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8137
8138         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8139         // accepting the inbound channel request.
8140         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8141
8142         let events = nodes[1].node.get_and_clear_pending_events();
8143         match events[0] {
8144                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8145                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, 23).unwrap();
8146                 }
8147                 _ => panic!("Unexpected event"),
8148         }
8149
8150         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8151         assert_eq!(accept_msg_ev.len(), 1);
8152
8153         match accept_msg_ev[0] {
8154                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8155                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8156                 }
8157                 _ => panic!("Unexpected event"),
8158         }
8159
8160         nodes[1].node.force_close_channel(&temp_channel_id).unwrap();
8161
8162         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8163         assert_eq!(close_msg_ev.len(), 1);
8164
8165         let events = nodes[1].node.get_and_clear_pending_events();
8166         match events[0] {
8167                 Event::ChannelClosed { user_channel_id, .. } => {
8168                         assert_eq!(user_channel_id, 23);
8169                 }
8170                 _ => panic!("Unexpected event"),
8171         }
8172 }
8173
8174 #[test]
8175 fn test_manually_reject_inbound_channel_request() {
8176         let mut manually_accept_conf = UserConfig::default();
8177         manually_accept_conf.manually_accept_inbound_channels = true;
8178         let chanmon_cfgs = create_chanmon_cfgs(2);
8179         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8180         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8181         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8182
8183         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8184         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8185
8186         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8187
8188         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8189         // rejecting the inbound channel request.
8190         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8191
8192         let events = nodes[1].node.get_and_clear_pending_events();
8193         match events[0] {
8194                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8195                         nodes[1].node.force_close_channel(&temporary_channel_id).unwrap();
8196                 }
8197                 _ => panic!("Unexpected event"),
8198         }
8199
8200         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8201         assert_eq!(close_msg_ev.len(), 1);
8202
8203         match close_msg_ev[0] {
8204                 MessageSendEvent::HandleError { ref node_id, .. } => {
8205                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8206                 }
8207                 _ => panic!("Unexpected event"),
8208         }
8209         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8210 }
8211
8212 #[test]
8213 fn test_reject_funding_before_inbound_channel_accepted() {
8214         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8215         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8216         // the node operator before the counterparty sends a `FundingCreated` message. If a
8217         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8218         // and the channel should be closed.
8219         let mut manually_accept_conf = UserConfig::default();
8220         manually_accept_conf.manually_accept_inbound_channels = true;
8221         let chanmon_cfgs = create_chanmon_cfgs(2);
8222         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8223         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8224         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8225
8226         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8227         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8228         let temp_channel_id = res.temporary_channel_id;
8229
8230         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8231
8232         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8233         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8234
8235         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8236         nodes[1].node.get_and_clear_pending_events();
8237
8238         // Get the `AcceptChannel` message of `nodes[1]` without calling
8239         // `ChannelManager::accept_inbound_channel`, which generates a
8240         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8241         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8242         // succeed when `nodes[0]` is passed to it.
8243         {
8244                 let mut lock;
8245                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8246                 let accept_chan_msg = channel.get_accept_channel_message();
8247                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8248         }
8249
8250         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8251
8252         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8253         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8254
8255         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8256         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8257
8258         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8259         assert_eq!(close_msg_ev.len(), 1);
8260
8261         let expected_err = "FundingCreated message received before the channel was accepted";
8262         match close_msg_ev[0] {
8263                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8264                         assert_eq!(msg.channel_id, temp_channel_id);
8265                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8266                         assert_eq!(msg.data, expected_err);
8267                 }
8268                 _ => panic!("Unexpected event"),
8269         }
8270
8271         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8272 }
8273
8274 #[test]
8275 fn test_can_not_accept_inbound_channel_twice() {
8276         let mut manually_accept_conf = UserConfig::default();
8277         manually_accept_conf.manually_accept_inbound_channels = true;
8278         let chanmon_cfgs = create_chanmon_cfgs(2);
8279         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8280         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8281         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8282
8283         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8284         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8285
8286         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8287
8288         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8289         // accepting the inbound channel request.
8290         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8291
8292         let events = nodes[1].node.get_and_clear_pending_events();
8293         match events[0] {
8294                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8295                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, 0).unwrap();
8296                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, 0);
8297                         match api_res {
8298                                 Err(APIError::APIMisuseError { err }) => {
8299                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8300                                 },
8301                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8302                                 Err(_) => panic!("Unexpected Error"),
8303                         }
8304                 }
8305                 _ => panic!("Unexpected event"),
8306         }
8307
8308         // Ensure that the channel wasn't closed after attempting to accept it twice.
8309         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8310         assert_eq!(accept_msg_ev.len(), 1);
8311
8312         match accept_msg_ev[0] {
8313                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8314                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8315                 }
8316                 _ => panic!("Unexpected event"),
8317         }
8318 }
8319
8320 #[test]
8321 fn test_can_not_accept_unknown_inbound_channel() {
8322         let chanmon_cfg = create_chanmon_cfgs(1);
8323         let node_cfg = create_node_cfgs(1, &chanmon_cfg);
8324         let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
8325         let node = create_network(1, &node_cfg, &node_chanmgr)[0].node;
8326
8327         let unknown_channel_id = [0; 32];
8328         let api_res = node.accept_inbound_channel(&unknown_channel_id, 0);
8329         match api_res {
8330                 Err(APIError::ChannelUnavailable { err }) => {
8331                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8332                 },
8333                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8334                 Err(_) => panic!("Unexpected Error"),
8335         }
8336 }
8337
8338 #[test]
8339 fn test_simple_mpp() {
8340         // Simple test of sending a multi-path payment.
8341         let chanmon_cfgs = create_chanmon_cfgs(4);
8342         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8343         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8344         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8345
8346         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8347         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8348         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8349         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8350
8351         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8352         let path = route.paths[0].clone();
8353         route.paths.push(path);
8354         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8355         route.paths[0][0].short_channel_id = chan_1_id;
8356         route.paths[0][1].short_channel_id = chan_3_id;
8357         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8358         route.paths[1][0].short_channel_id = chan_2_id;
8359         route.paths[1][1].short_channel_id = chan_4_id;
8360         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8361         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8362 }
8363
8364 #[test]
8365 fn test_preimage_storage() {
8366         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8367         let chanmon_cfgs = create_chanmon_cfgs(2);
8368         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8369         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8370         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8371
8372         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8373
8374         {
8375                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8376                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8377                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8378                 check_added_monitors!(nodes[0], 1);
8379                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8380                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8381                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8382                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8383         }
8384         // Note that after leaving the above scope we have no knowledge of any arguments or return
8385         // values from previous calls.
8386         expect_pending_htlcs_forwardable!(nodes[1]);
8387         let events = nodes[1].node.get_and_clear_pending_events();
8388         assert_eq!(events.len(), 1);
8389         match events[0] {
8390                 Event::PaymentReceived { ref purpose, .. } => {
8391                         match &purpose {
8392                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8393                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8394                                 },
8395                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8396                         }
8397                 },
8398                 _ => panic!("Unexpected event"),
8399         }
8400 }
8401
8402 #[test]
8403 #[allow(deprecated)]
8404 fn test_secret_timeout() {
8405         // Simple test of payment secret storage time outs. After
8406         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8407         let chanmon_cfgs = create_chanmon_cfgs(2);
8408         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8409         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8410         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8411
8412         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8413
8414         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8415
8416         // We should fail to register the same payment hash twice, at least until we've connected a
8417         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8418         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8419                 assert_eq!(err, "Duplicate payment hash");
8420         } else { panic!(); }
8421         let mut block = {
8422                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8423                 Block {
8424                         header: BlockHeader {
8425                                 version: 0x2000000,
8426                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8427                                 merkle_root: Default::default(),
8428                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8429                         txdata: vec![],
8430                 }
8431         };
8432         connect_block(&nodes[1], &block);
8433         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8434                 assert_eq!(err, "Duplicate payment hash");
8435         } else { panic!(); }
8436
8437         // If we then connect the second block, we should be able to register the same payment hash
8438         // again (this time getting a new payment secret).
8439         block.header.prev_blockhash = block.header.block_hash();
8440         block.header.time += 1;
8441         connect_block(&nodes[1], &block);
8442         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8443         assert_ne!(payment_secret_1, our_payment_secret);
8444
8445         {
8446                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8447                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8448                 check_added_monitors!(nodes[0], 1);
8449                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8450                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8451                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8452                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8453         }
8454         // Note that after leaving the above scope we have no knowledge of any arguments or return
8455         // values from previous calls.
8456         expect_pending_htlcs_forwardable!(nodes[1]);
8457         let events = nodes[1].node.get_and_clear_pending_events();
8458         assert_eq!(events.len(), 1);
8459         match events[0] {
8460                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8461                         assert!(payment_preimage.is_none());
8462                         assert_eq!(payment_secret, our_payment_secret);
8463                         // We don't actually have the payment preimage with which to claim this payment!
8464                 },
8465                 _ => panic!("Unexpected event"),
8466         }
8467 }
8468
8469 #[test]
8470 fn test_bad_secret_hash() {
8471         // Simple test of unregistered payment hash/invalid payment secret handling
8472         let chanmon_cfgs = create_chanmon_cfgs(2);
8473         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8474         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8475         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8476
8477         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8478
8479         let random_payment_hash = PaymentHash([42; 32]);
8480         let random_payment_secret = PaymentSecret([43; 32]);
8481         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8482         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8483
8484         // All the below cases should end up being handled exactly identically, so we macro the
8485         // resulting events.
8486         macro_rules! handle_unknown_invalid_payment_data {
8487                 () => {
8488                         check_added_monitors!(nodes[0], 1);
8489                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8490                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8491                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8492                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8493
8494                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8495                         // again to process the pending backwards-failure of the HTLC
8496                         expect_pending_htlcs_forwardable!(nodes[1]);
8497                         expect_pending_htlcs_forwardable!(nodes[1]);
8498                         check_added_monitors!(nodes[1], 1);
8499
8500                         // We should fail the payment back
8501                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8502                         match events.pop().unwrap() {
8503                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8504                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8505                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8506                                 },
8507                                 _ => panic!("Unexpected event"),
8508                         }
8509                 }
8510         }
8511
8512         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8513         // Error data is the HTLC value (100,000) and current block height
8514         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8515
8516         // Send a payment with the right payment hash but the wrong payment secret
8517         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8518         handle_unknown_invalid_payment_data!();
8519         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8520
8521         // Send a payment with a random payment hash, but the right payment secret
8522         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8523         handle_unknown_invalid_payment_data!();
8524         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8525
8526         // Send a payment with a random payment hash and random payment secret
8527         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8528         handle_unknown_invalid_payment_data!();
8529         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8530 }
8531
8532 #[test]
8533 fn test_update_err_monitor_lockdown() {
8534         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8535         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8536         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8537         //
8538         // This scenario may happen in a watchtower setup, where watchtower process a block height
8539         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8540         // commitment at same time.
8541
8542         let chanmon_cfgs = create_chanmon_cfgs(2);
8543         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8544         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8545         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8546
8547         // Create some initial channel
8548         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8549         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8550
8551         // Rebalance the network to generate htlc in the two directions
8552         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8553
8554         // Route a HTLC from node 0 to node 1 (but don't settle)
8555         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8556
8557         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8558         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8559         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8560         let persister = test_utils::TestPersister::new();
8561         let watchtower = {
8562                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8563                 let mut w = test_utils::TestVecWriter(Vec::new());
8564                 monitor.write(&mut w).unwrap();
8565                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8566                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8567                 assert!(new_monitor == *monitor);
8568                 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);
8569                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8570                 watchtower
8571         };
8572         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8573         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8574         // transaction lock time requirements here.
8575         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8576         watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8577
8578         // Try to update ChannelMonitor
8579         assert!(nodes[1].node.claim_funds(preimage));
8580         check_added_monitors!(nodes[1], 1);
8581         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8582         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8583         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8584         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8585                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8586                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8587                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8588                 } else { assert!(false); }
8589         } else { assert!(false); };
8590         // Our local monitor is in-sync and hasn't processed yet timeout
8591         check_added_monitors!(nodes[0], 1);
8592         let events = nodes[0].node.get_and_clear_pending_events();
8593         assert_eq!(events.len(), 1);
8594 }
8595
8596 #[test]
8597 fn test_concurrent_monitor_claim() {
8598         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8599         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8600         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8601         // state N+1 confirms. Alice claims output from state N+1.
8602
8603         let chanmon_cfgs = create_chanmon_cfgs(2);
8604         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8605         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8606         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8607
8608         // Create some initial channel
8609         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8610         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8611
8612         // Rebalance the network to generate htlc in the two directions
8613         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8614
8615         // Route a HTLC from node 0 to node 1 (but don't settle)
8616         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8617
8618         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8619         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8620         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8621         let persister = test_utils::TestPersister::new();
8622         let watchtower_alice = {
8623                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8624                 let mut w = test_utils::TestVecWriter(Vec::new());
8625                 monitor.write(&mut w).unwrap();
8626                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8627                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8628                 assert!(new_monitor == *monitor);
8629                 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);
8630                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8631                 watchtower
8632         };
8633         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8634         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8635         // transaction lock time requirements here.
8636         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8637         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8638
8639         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8640         {
8641                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8642                 assert_eq!(txn.len(), 2);
8643                 txn.clear();
8644         }
8645
8646         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8647         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8648         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8649         let persister = test_utils::TestPersister::new();
8650         let watchtower_bob = {
8651                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8652                 let mut w = test_utils::TestVecWriter(Vec::new());
8653                 monitor.write(&mut w).unwrap();
8654                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8655                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8656                 assert!(new_monitor == *monitor);
8657                 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);
8658                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8659                 watchtower
8660         };
8661         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8662         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8663
8664         // Route another payment to generate another update with still previous HTLC pending
8665         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8666         {
8667                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8668         }
8669         check_added_monitors!(nodes[1], 1);
8670
8671         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8672         assert_eq!(updates.update_add_htlcs.len(), 1);
8673         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8674         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8675                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8676                         // Watchtower Alice should already have seen the block and reject the update
8677                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8678                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8679                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8680                 } else { assert!(false); }
8681         } else { assert!(false); };
8682         // Our local monitor is in-sync and hasn't processed yet timeout
8683         check_added_monitors!(nodes[0], 1);
8684
8685         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8686         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8687         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8688
8689         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8690         let bob_state_y;
8691         {
8692                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8693                 assert_eq!(txn.len(), 2);
8694                 bob_state_y = txn[0].clone();
8695                 txn.clear();
8696         };
8697
8698         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8699         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8700         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);
8701         {
8702                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8703                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8704                 // the onchain detection of the HTLC output
8705                 assert_eq!(htlc_txn.len(), 2);
8706                 check_spends!(htlc_txn[0], bob_state_y);
8707                 check_spends!(htlc_txn[1], bob_state_y);
8708         }
8709 }
8710
8711 #[test]
8712 fn test_pre_lockin_no_chan_closed_update() {
8713         // Test that if a peer closes a channel in response to a funding_created message we don't
8714         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8715         // message).
8716         //
8717         // Doing so would imply a channel monitor update before the initial channel monitor
8718         // registration, violating our API guarantees.
8719         //
8720         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8721         // then opening a second channel with the same funding output as the first (which is not
8722         // rejected because the first channel does not exist in the ChannelManager) and closing it
8723         // before receiving funding_signed.
8724         let chanmon_cfgs = create_chanmon_cfgs(2);
8725         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8726         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8727         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8728
8729         // Create an initial channel
8730         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8731         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8732         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8733         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8734         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8735
8736         // Move the first channel through the funding flow...
8737         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8738
8739         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8740         check_added_monitors!(nodes[0], 0);
8741
8742         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8743         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8744         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8745         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8746         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8747 }
8748
8749 #[test]
8750 fn test_htlc_no_detection() {
8751         // This test is a mutation to underscore the detection logic bug we had
8752         // before #653. HTLC value routed is above the remaining balance, thus
8753         // inverting HTLC and `to_remote` output. HTLC will come second and
8754         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8755         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8756         // outputs order detection for correct spending children filtring.
8757
8758         let chanmon_cfgs = create_chanmon_cfgs(2);
8759         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8760         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8761         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8762
8763         // Create some initial channels
8764         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8765
8766         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8767         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8768         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8769         assert_eq!(local_txn[0].input.len(), 1);
8770         assert_eq!(local_txn[0].output.len(), 3);
8771         check_spends!(local_txn[0], chan_1.3);
8772
8773         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8774         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8775         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8776         // We deliberately connect the local tx twice as this should provoke a failure calling
8777         // this test before #653 fix.
8778         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);
8779         check_closed_broadcast!(nodes[0], true);
8780         check_added_monitors!(nodes[0], 1);
8781         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8782         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8783
8784         let htlc_timeout = {
8785                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8786                 assert_eq!(node_txn[1].input.len(), 1);
8787                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8788                 check_spends!(node_txn[1], local_txn[0]);
8789                 node_txn[1].clone()
8790         };
8791
8792         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8793         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8794         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8795         expect_payment_failed!(nodes[0], our_payment_hash, true);
8796 }
8797
8798 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8799         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8800         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8801         // Carol, Alice would be the upstream node, and Carol the downstream.)
8802         //
8803         // Steps of the test:
8804         // 1) Alice sends a HTLC to Carol through Bob.
8805         // 2) Carol doesn't settle the HTLC.
8806         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8807         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8808         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8809         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8810         // 5) Carol release the preimage to Bob off-chain.
8811         // 6) Bob claims the offered output on the broadcasted commitment.
8812         let chanmon_cfgs = create_chanmon_cfgs(3);
8813         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8814         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8815         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8816
8817         // Create some initial channels
8818         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8819         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8820
8821         // Steps (1) and (2):
8822         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8823         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8824
8825         // Check that Alice's commitment transaction now contains an output for this HTLC.
8826         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8827         check_spends!(alice_txn[0], chan_ab.3);
8828         assert_eq!(alice_txn[0].output.len(), 2);
8829         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8830         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8831         assert_eq!(alice_txn.len(), 2);
8832
8833         // Steps (3) and (4):
8834         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8835         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8836         let mut force_closing_node = 0; // Alice force-closes
8837         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8838         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8839         check_closed_broadcast!(nodes[force_closing_node], true);
8840         check_added_monitors!(nodes[force_closing_node], 1);
8841         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8842         if go_onchain_before_fulfill {
8843                 let txn_to_broadcast = match broadcast_alice {
8844                         true => alice_txn.clone(),
8845                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8846                 };
8847                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8848                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8849                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8850                 if broadcast_alice {
8851                         check_closed_broadcast!(nodes[1], true);
8852                         check_added_monitors!(nodes[1], 1);
8853                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8854                 }
8855                 assert_eq!(bob_txn.len(), 1);
8856                 check_spends!(bob_txn[0], chan_ab.3);
8857         }
8858
8859         // Step (5):
8860         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8861         // process of removing the HTLC from their commitment transactions.
8862         assert!(nodes[2].node.claim_funds(payment_preimage));
8863         check_added_monitors!(nodes[2], 1);
8864         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8865         assert!(carol_updates.update_add_htlcs.is_empty());
8866         assert!(carol_updates.update_fail_htlcs.is_empty());
8867         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8868         assert!(carol_updates.update_fee.is_none());
8869         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8870
8871         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8872         expect_payment_forwarded!(nodes[1], nodes[0], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8873         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8874         if !go_onchain_before_fulfill && broadcast_alice {
8875                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8876                 assert_eq!(events.len(), 1);
8877                 match events[0] {
8878                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8879                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8880                         },
8881                         _ => panic!("Unexpected event"),
8882                 };
8883         }
8884         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8885         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8886         // Carol<->Bob's updated commitment transaction info.
8887         check_added_monitors!(nodes[1], 2);
8888
8889         let events = nodes[1].node.get_and_clear_pending_msg_events();
8890         assert_eq!(events.len(), 2);
8891         let bob_revocation = match events[0] {
8892                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8893                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8894                         (*msg).clone()
8895                 },
8896                 _ => panic!("Unexpected event"),
8897         };
8898         let bob_updates = match events[1] {
8899                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8900                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8901                         (*updates).clone()
8902                 },
8903                 _ => panic!("Unexpected event"),
8904         };
8905
8906         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8907         check_added_monitors!(nodes[2], 1);
8908         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8909         check_added_monitors!(nodes[2], 1);
8910
8911         let events = nodes[2].node.get_and_clear_pending_msg_events();
8912         assert_eq!(events.len(), 1);
8913         let carol_revocation = match events[0] {
8914                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8915                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8916                         (*msg).clone()
8917                 },
8918                 _ => panic!("Unexpected event"),
8919         };
8920         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8921         check_added_monitors!(nodes[1], 1);
8922
8923         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8924         // here's where we put said channel's commitment tx on-chain.
8925         let mut txn_to_broadcast = alice_txn.clone();
8926         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8927         if !go_onchain_before_fulfill {
8928                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8929                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8930                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8931                 if broadcast_alice {
8932                         check_closed_broadcast!(nodes[1], true);
8933                         check_added_monitors!(nodes[1], 1);
8934                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8935                 }
8936                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8937                 if broadcast_alice {
8938                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8939                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8940                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8941                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8942                         // broadcasted.
8943                         assert_eq!(bob_txn.len(), 3);
8944                         check_spends!(bob_txn[1], chan_ab.3);
8945                 } else {
8946                         assert_eq!(bob_txn.len(), 2);
8947                         check_spends!(bob_txn[0], chan_ab.3);
8948                 }
8949         }
8950
8951         // Step (6):
8952         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8953         // broadcasted commitment transaction.
8954         {
8955                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8956                 if go_onchain_before_fulfill {
8957                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8958                         assert_eq!(bob_txn.len(), 2);
8959                 }
8960                 let script_weight = match broadcast_alice {
8961                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8962                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8963                 };
8964                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8965                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8966                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8967                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8968                 if broadcast_alice && !go_onchain_before_fulfill {
8969                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8970                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8971                 } else {
8972                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8973                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8974                 }
8975         }
8976 }
8977
8978 #[test]
8979 fn test_onchain_htlc_settlement_after_close() {
8980         do_test_onchain_htlc_settlement_after_close(true, true);
8981         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8982         do_test_onchain_htlc_settlement_after_close(true, false);
8983         do_test_onchain_htlc_settlement_after_close(false, false);
8984 }
8985
8986 #[test]
8987 fn test_duplicate_chan_id() {
8988         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8989         // already open we reject it and keep the old channel.
8990         //
8991         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8992         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8993         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8994         // updating logic for the existing channel.
8995         let chanmon_cfgs = create_chanmon_cfgs(2);
8996         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8997         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8998         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8999
9000         // Create an initial channel
9001         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9002         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9003         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9004         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()));
9005
9006         // Try to create a second channel with the same temporary_channel_id as the first and check
9007         // that it is rejected.
9008         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9009         {
9010                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9011                 assert_eq!(events.len(), 1);
9012                 match events[0] {
9013                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9014                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9015                                 // first (valid) and second (invalid) channels are closed, given they both have
9016                                 // the same non-temporary channel_id. However, currently we do not, so we just
9017                                 // move forward with it.
9018                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9019                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9020                         },
9021                         _ => panic!("Unexpected event"),
9022                 }
9023         }
9024
9025         // Move the first channel through the funding flow...
9026         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
9027
9028         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9029         check_added_monitors!(nodes[0], 0);
9030
9031         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9032         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9033         {
9034                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9035                 assert_eq!(added_monitors.len(), 1);
9036                 assert_eq!(added_monitors[0].0, funding_output);
9037                 added_monitors.clear();
9038         }
9039         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9040
9041         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9042         let channel_id = funding_outpoint.to_channel_id();
9043
9044         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9045         // temporary one).
9046
9047         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9048         // Technically this is allowed by the spec, but we don't support it and there's little reason
9049         // to. Still, it shouldn't cause any other issues.
9050         open_chan_msg.temporary_channel_id = channel_id;
9051         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9052         {
9053                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9054                 assert_eq!(events.len(), 1);
9055                 match events[0] {
9056                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9057                                 // Technically, at this point, nodes[1] would be justified in thinking both
9058                                 // channels are closed, but currently we do not, so we just move forward with it.
9059                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9060                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9061                         },
9062                         _ => panic!("Unexpected event"),
9063                 }
9064         }
9065
9066         // Now try to create a second channel which has a duplicate funding output.
9067         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9068         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9069         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9070         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()));
9071         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
9072
9073         let funding_created = {
9074                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9075                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
9076                 let logger = test_utils::TestLogger::new();
9077                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9078         };
9079         check_added_monitors!(nodes[0], 0);
9080         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9081         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9082         // still needs to be cleared here.
9083         check_added_monitors!(nodes[1], 1);
9084
9085         // ...still, nodes[1] will reject the duplicate channel.
9086         {
9087                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9088                 assert_eq!(events.len(), 1);
9089                 match events[0] {
9090                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9091                                 // Technically, at this point, nodes[1] would be justified in thinking both
9092                                 // channels are closed, but currently we do not, so we just move forward with it.
9093                                 assert_eq!(msg.channel_id, channel_id);
9094                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9095                         },
9096                         _ => panic!("Unexpected event"),
9097                 }
9098         }
9099
9100         // finally, finish creating the original channel and send a payment over it to make sure
9101         // everything is functional.
9102         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9103         {
9104                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9105                 assert_eq!(added_monitors.len(), 1);
9106                 assert_eq!(added_monitors[0].0, funding_output);
9107                 added_monitors.clear();
9108         }
9109
9110         let events_4 = nodes[0].node.get_and_clear_pending_events();
9111         assert_eq!(events_4.len(), 0);
9112         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9113         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9114
9115         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9116         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9117         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9118         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9119 }
9120
9121 #[test]
9122 fn test_error_chans_closed() {
9123         // Test that we properly handle error messages, closing appropriate channels.
9124         //
9125         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9126         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9127         // we can test various edge cases around it to ensure we don't regress.
9128         let chanmon_cfgs = create_chanmon_cfgs(3);
9129         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9130         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9131         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9132
9133         // Create some initial channels
9134         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9135         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9136         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9137
9138         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9139         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9140         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9141
9142         // Closing a channel from a different peer has no effect
9143         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9144         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9145
9146         // Closing one channel doesn't impact others
9147         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9148         check_added_monitors!(nodes[0], 1);
9149         check_closed_broadcast!(nodes[0], false);
9150         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9151         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9152         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9153         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);
9154         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);
9155
9156         // A null channel ID should close all channels
9157         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9158         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9159         check_added_monitors!(nodes[0], 2);
9160         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9161         let events = nodes[0].node.get_and_clear_pending_msg_events();
9162         assert_eq!(events.len(), 2);
9163         match events[0] {
9164                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9165                         assert_eq!(msg.contents.flags & 2, 2);
9166                 },
9167                 _ => panic!("Unexpected event"),
9168         }
9169         match events[1] {
9170                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9171                         assert_eq!(msg.contents.flags & 2, 2);
9172                 },
9173                 _ => panic!("Unexpected event"),
9174         }
9175         // Note that at this point users of a standard PeerHandler will end up calling
9176         // peer_disconnected with no_connection_possible set to false, duplicating the
9177         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9178         // users with their own peer handling logic. We duplicate the call here, however.
9179         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9180         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9181
9182         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9183         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9184         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9185 }
9186
9187 #[test]
9188 fn test_invalid_funding_tx() {
9189         // Test that we properly handle invalid funding transactions sent to us from a peer.
9190         //
9191         // Previously, all other major lightning implementations had failed to properly sanitize
9192         // funding transactions from their counterparties, leading to a multi-implementation critical
9193         // security vulnerability (though we always sanitized properly, we've previously had
9194         // un-released crashes in the sanitization process).
9195         let chanmon_cfgs = create_chanmon_cfgs(2);
9196         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9197         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9198         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9199
9200         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9201         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()));
9202         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()));
9203
9204         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
9205         for output in tx.output.iter_mut() {
9206                 // Make the confirmed funding transaction have a bogus script_pubkey
9207                 output.script_pubkey = bitcoin::Script::new();
9208         }
9209
9210         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
9211         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()));
9212         check_added_monitors!(nodes[1], 1);
9213
9214         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()));
9215         check_added_monitors!(nodes[0], 1);
9216
9217         let events_1 = nodes[0].node.get_and_clear_pending_events();
9218         assert_eq!(events_1.len(), 0);
9219
9220         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9221         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9222         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9223
9224         let expected_err = "funding tx had wrong script/value or output index";
9225         confirm_transaction_at(&nodes[1], &tx, 1);
9226         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9227         check_added_monitors!(nodes[1], 1);
9228         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9229         assert_eq!(events_2.len(), 1);
9230         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9231                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9232                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9233                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9234                 } else { panic!(); }
9235         } else { panic!(); }
9236         assert_eq!(nodes[1].node.list_channels().len(), 0);
9237 }
9238
9239 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9240         // In the first version of the chain::Confirm interface, after a refactor was made to not
9241         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9242         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9243         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9244         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9245         // spending transaction until height N+1 (or greater). This was due to the way
9246         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9247         // spending transaction at the height the input transaction was confirmed at, not whether we
9248         // should broadcast a spending transaction at the current height.
9249         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9250         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9251         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9252         // until we learned about an additional block.
9253         //
9254         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9255         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9256         let chanmon_cfgs = create_chanmon_cfgs(3);
9257         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9258         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9259         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9260         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9261
9262         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9263         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9264         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9265         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9266         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9267
9268         nodes[1].node.force_close_channel(&channel_id).unwrap();
9269         check_closed_broadcast!(nodes[1], true);
9270         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9271         check_added_monitors!(nodes[1], 1);
9272         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9273         assert_eq!(node_txn.len(), 1);
9274
9275         let conf_height = nodes[1].best_block_info().1;
9276         if !test_height_before_timelock {
9277                 connect_blocks(&nodes[1], 24 * 6);
9278         }
9279         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9280                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9281         if test_height_before_timelock {
9282                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9283                 // generate any events or broadcast any transactions
9284                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9285                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9286         } else {
9287                 // We should broadcast an HTLC transaction spending our funding transaction first
9288                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9289                 assert_eq!(spending_txn.len(), 2);
9290                 assert_eq!(spending_txn[0], node_txn[0]);
9291                 check_spends!(spending_txn[1], node_txn[0]);
9292                 // We should also generate a SpendableOutputs event with the to_self output (as its
9293                 // timelock is up).
9294                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9295                 assert_eq!(descriptor_spend_txn.len(), 1);
9296
9297                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9298                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9299                 // additional block built on top of the current chain.
9300                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9301                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9302                 expect_pending_htlcs_forwardable!(nodes[1]);
9303                 check_added_monitors!(nodes[1], 1);
9304
9305                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9306                 assert!(updates.update_add_htlcs.is_empty());
9307                 assert!(updates.update_fulfill_htlcs.is_empty());
9308                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9309                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9310                 assert!(updates.update_fee.is_none());
9311                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9312                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9313                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9314         }
9315 }
9316
9317 #[test]
9318 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9319         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9320         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9321 }
9322
9323 #[test]
9324 fn test_forwardable_regen() {
9325         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9326         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9327         // HTLCs.
9328         // We test it for both payment receipt and payment forwarding.
9329
9330         let chanmon_cfgs = create_chanmon_cfgs(3);
9331         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9332         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9333         let persister: test_utils::TestPersister;
9334         let new_chain_monitor: test_utils::TestChainMonitor;
9335         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9336         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9337         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9338         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9339
9340         // First send a payment to nodes[1]
9341         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9342         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9343         check_added_monitors!(nodes[0], 1);
9344
9345         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9346         assert_eq!(events.len(), 1);
9347         let payment_event = SendEvent::from_event(events.pop().unwrap());
9348         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9349         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9350
9351         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9352
9353         // Next send a payment which is forwarded by nodes[1]
9354         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9355         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9356         check_added_monitors!(nodes[0], 1);
9357
9358         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9359         assert_eq!(events.len(), 1);
9360         let payment_event = SendEvent::from_event(events.pop().unwrap());
9361         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9362         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9363
9364         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9365         // generated
9366         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9367
9368         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9369         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9370         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9371
9372         let nodes_1_serialized = nodes[1].node.encode();
9373         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9374         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9375         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9376         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9377
9378         persister = test_utils::TestPersister::new();
9379         let keys_manager = &chanmon_cfgs[1].keys_manager;
9380         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);
9381         nodes[1].chain_monitor = &new_chain_monitor;
9382
9383         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9384         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9385                 &mut chan_0_monitor_read, keys_manager).unwrap();
9386         assert!(chan_0_monitor_read.is_empty());
9387         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9388         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9389                 &mut chan_1_monitor_read, keys_manager).unwrap();
9390         assert!(chan_1_monitor_read.is_empty());
9391
9392         let mut nodes_1_read = &nodes_1_serialized[..];
9393         let (_, nodes_1_deserialized_tmp) = {
9394                 let mut channel_monitors = HashMap::new();
9395                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9396                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9397                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9398                         default_config: UserConfig::default(),
9399                         keys_manager,
9400                         fee_estimator: node_cfgs[1].fee_estimator,
9401                         chain_monitor: nodes[1].chain_monitor,
9402                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9403                         logger: nodes[1].logger,
9404                         channel_monitors,
9405                 }).unwrap()
9406         };
9407         nodes_1_deserialized = nodes_1_deserialized_tmp;
9408         assert!(nodes_1_read.is_empty());
9409
9410         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9411         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9412         nodes[1].node = &nodes_1_deserialized;
9413         check_added_monitors!(nodes[1], 2);
9414
9415         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9416         // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9417         // the commitment state.
9418         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9419
9420         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9421
9422         expect_pending_htlcs_forwardable!(nodes[1]);
9423         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9424         check_added_monitors!(nodes[1], 1);
9425
9426         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9427         assert_eq!(events.len(), 1);
9428         let payment_event = SendEvent::from_event(events.pop().unwrap());
9429         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9430         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9431         expect_pending_htlcs_forwardable!(nodes[2]);
9432         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9433
9434         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9435         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9436 }
9437
9438 #[test]
9439 fn test_dup_htlc_second_fail_panic() {
9440         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9441         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9442         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9443         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9444         let chanmon_cfgs = create_chanmon_cfgs(2);
9445         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9446         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9447         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9448
9449         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9450
9451         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9452                 .with_features(InvoiceFeatures::known());
9453         let scorer = test_utils::TestScorer::with_penalty(0);
9454         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9455         let route = get_route(
9456                 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
9457                 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
9458                 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9459
9460         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9461
9462         {
9463                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9464                 check_added_monitors!(nodes[0], 1);
9465                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9466                 assert_eq!(events.len(), 1);
9467                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9468                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9469                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9470         }
9471         expect_pending_htlcs_forwardable!(nodes[1]);
9472         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9473
9474         {
9475                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9476                 check_added_monitors!(nodes[0], 1);
9477                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9478                 assert_eq!(events.len(), 1);
9479                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9480                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9481                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9482                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9483                 // assume the second is a privacy attack (no longer particularly relevant
9484                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9485                 // the first HTLC delivered above.
9486         }
9487
9488         // Now we go fail back the first HTLC from the user end.
9489         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9490         nodes[1].node.process_pending_htlc_forwards();
9491         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9492
9493         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9494         nodes[1].node.process_pending_htlc_forwards();
9495
9496         check_added_monitors!(nodes[1], 1);
9497         let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9498         assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9499
9500         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9501         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9502         commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9503
9504         let failure_events = nodes[0].node.get_and_clear_pending_events();
9505         assert_eq!(failure_events.len(), 2);
9506         if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9507         if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9508 }
9509
9510 #[test]
9511 fn test_keysend_payments_to_public_node() {
9512         let chanmon_cfgs = create_chanmon_cfgs(2);
9513         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9514         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9515         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9516
9517         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9518         let network_graph = nodes[0].network_graph;
9519         let payer_pubkey = nodes[0].node.get_our_node_id();
9520         let payee_pubkey = nodes[1].node.get_our_node_id();
9521         let route_params = RouteParameters {
9522                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9523                 final_value_msat: 10000,
9524                 final_cltv_expiry_delta: 40,
9525         };
9526         let scorer = test_utils::TestScorer::with_penalty(0);
9527         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9528         let route = find_route(&payer_pubkey, &route_params, network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9529
9530         let test_preimage = PaymentPreimage([42; 32]);
9531         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9532         check_added_monitors!(nodes[0], 1);
9533         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9534         assert_eq!(events.len(), 1);
9535         let event = events.pop().unwrap();
9536         let path = vec![&nodes[1]];
9537         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9538         claim_payment(&nodes[0], &path, test_preimage);
9539 }
9540
9541 #[test]
9542 fn test_keysend_payments_to_private_node() {
9543         let chanmon_cfgs = create_chanmon_cfgs(2);
9544         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9545         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9546         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9547
9548         let payer_pubkey = nodes[0].node.get_our_node_id();
9549         let payee_pubkey = nodes[1].node.get_our_node_id();
9550         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9551         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9552
9553         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9554         let route_params = RouteParameters {
9555                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9556                 final_value_msat: 10000,
9557                 final_cltv_expiry_delta: 40,
9558         };
9559         let network_graph = nodes[0].network_graph;
9560         let first_hops = nodes[0].node.list_usable_channels();
9561         let scorer = test_utils::TestScorer::with_penalty(0);
9562         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9563         let route = find_route(
9564                 &payer_pubkey, &route_params, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9565                 nodes[0].logger, &scorer, &random_seed_bytes
9566         ).unwrap();
9567
9568         let test_preimage = PaymentPreimage([42; 32]);
9569         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9570         check_added_monitors!(nodes[0], 1);
9571         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9572         assert_eq!(events.len(), 1);
9573         let event = events.pop().unwrap();
9574         let path = vec![&nodes[1]];
9575         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9576         claim_payment(&nodes[0], &path, test_preimage);
9577 }
9578
9579 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9580 #[derive(Clone, Copy, PartialEq)]
9581 enum ExposureEvent {
9582         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9583         AtHTLCForward,
9584         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9585         AtHTLCReception,
9586         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9587         AtUpdateFeeOutbound,
9588 }
9589
9590 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9591         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9592         // policy.
9593         //
9594         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9595         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9596         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9597         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9598         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9599         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9600         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9601         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9602
9603         let chanmon_cfgs = create_chanmon_cfgs(2);
9604         let mut config = test_default_channel_config();
9605         config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9606         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9607         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9608         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9609
9610         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9611         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9612         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9613         open_channel.max_accepted_htlcs = 60;
9614         if on_holder_tx {
9615                 open_channel.dust_limit_satoshis = 546;
9616         }
9617         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9618         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9619         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9620
9621         let opt_anchors = false;
9622
9623         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 1_000_000, 42);
9624
9625         if on_holder_tx {
9626                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9627                         chan.holder_dust_limit_satoshis = 546;
9628                 }
9629         }
9630
9631         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9632         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()));
9633         check_added_monitors!(nodes[1], 1);
9634
9635         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()));
9636         check_added_monitors!(nodes[0], 1);
9637
9638         let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9639         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9640         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9641
9642         let dust_buffer_feerate = {
9643                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9644                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9645                 chan.get_dust_buffer_feerate(None) as u64
9646         };
9647         let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(opt_anchors) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9648         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9649
9650         let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(opt_anchors) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9651         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9652
9653         let dust_htlc_on_counterparty_tx: u64 = 25;
9654         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9655
9656         if on_holder_tx {
9657                 if dust_outbound_balance {
9658                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9659                         // Outbound dust balance: 4372 sats
9660                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9661                         for i in 0..dust_outbound_htlc_on_holder_tx {
9662                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9663                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9664                         }
9665                 } else {
9666                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9667                         // Inbound dust balance: 4372 sats
9668                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9669                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9670                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9671                         }
9672                 }
9673         } else {
9674                 if dust_outbound_balance {
9675                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9676                         // Outbound dust balance: 5000 sats
9677                         for i in 0..dust_htlc_on_counterparty_tx {
9678                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9679                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9680                         }
9681                 } else {
9682                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9683                         // Inbound dust balance: 5000 sats
9684                         for _ in 0..dust_htlc_on_counterparty_tx {
9685                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9686                         }
9687                 }
9688         }
9689
9690         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9691         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9692                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat });
9693                 let mut config = UserConfig::default();
9694                 // With default dust exposure: 5000 sats
9695                 if on_holder_tx {
9696                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9697                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9698                         unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_options.max_dust_htlc_exposure_msat)));
9699                 } else {
9700                         unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_options.max_dust_htlc_exposure_msat)));
9701                 }
9702         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9703                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], if on_holder_tx { dust_inbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat });
9704                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9705                 check_added_monitors!(nodes[1], 1);
9706                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9707                 assert_eq!(events.len(), 1);
9708                 let payment_event = SendEvent::from_event(events.remove(0));
9709                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9710                 // With default dust exposure: 5000 sats
9711                 if on_holder_tx {
9712                         // Outbound dust balance: 6399 sats
9713                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9714                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9715                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_options.max_dust_htlc_exposure_msat), 1);
9716                 } else {
9717                         // Outbound dust balance: 5200 sats
9718                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_options.max_dust_htlc_exposure_msat), 1);
9719                 }
9720         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9721                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9722                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
9723                 {
9724                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9725                         *feerate_lock = *feerate_lock * 10;
9726                 }
9727                 nodes[0].node.timer_tick_occurred();
9728                 check_added_monitors!(nodes[0], 1);
9729                 nodes[0].logger.assert_log_contains("lightning::ln::channel".to_string(), "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure".to_string(), 1);
9730         }
9731
9732         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9733         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9734         added_monitors.clear();
9735 }
9736
9737 #[test]
9738 fn test_max_dust_htlc_exposure() {
9739         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9740         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9741         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9742         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9743         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9744         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9745         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9746         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9747         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9748         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9749         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9750         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9751 }