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