Relax the channel saturation limit if we can't find enough paths
[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::gossip::NetworkGraph;
27 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
28 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
29 use ln::msgs;
30 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, OptionalField, ErrorAction};
31 use util::enforcing_trait_impls::EnforcingSigner;
32 use util::{byte_utils, test_utils};
33 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
34 use util::errors::APIError;
35 use util::ser::{Writeable, ReadableArgs};
36 use util::config::UserConfig;
37
38 use bitcoin::hash_types::BlockHash;
39 use bitcoin::blockdata::block::{Block, BlockHeader};
40 use bitcoin::blockdata::script::{Builder, Script};
41 use bitcoin::blockdata::opcodes;
42 use bitcoin::blockdata::constants::genesis_block;
43 use bitcoin::network::constants::Network;
44 use bitcoin::{Transaction, TxIn, TxOut, Witness};
45 use bitcoin::OutPoint as BitcoinOutPoint;
46
47 use bitcoin::secp256k1::Secp256k1;
48 use bitcoin::secp256k1::{PublicKey,SecretKey};
49
50 use regex;
51
52 use io;
53 use prelude::*;
54 use alloc::collections::BTreeSet;
55 use core::default::Default;
56 use sync::{Arc, Mutex};
57
58 use ln::functional_test_utils::*;
59 use ln::chan_utils::CommitmentTransaction;
60
61 #[test]
62 fn test_insane_channel_opens() {
63         // Stand up a network of 2 nodes
64         use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
65         let mut cfg = UserConfig::default();
66         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
67         let chanmon_cfgs = create_chanmon_cfgs(2);
68         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
69         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
70         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
71
72         // Instantiate channel parameters where we push the maximum msats given our
73         // funding satoshis
74         let channel_value_sat = 31337; // same as funding satoshis
75         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
76         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
77
78         // Have node0 initiate a channel to node1 with aforementioned parameters
79         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
80
81         // Extract the channel open message from node0 to node1
82         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
83
84         // Test helper that asserts we get the correct error string given a mutator
85         // that supposedly makes the channel open message insane
86         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
87                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
88                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
89                 assert_eq!(msg_events.len(), 1);
90                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
91                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
92                         match action {
93                                 &ErrorAction::SendErrorMessage { .. } => {
94                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
95                                 },
96                                 _ => panic!("unexpected event!"),
97                         }
98                 } else { assert!(false); }
99         };
100
101         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
102
103         // Test all mutations that would make the channel open message insane
104         insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
105         insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
106
107         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
108
109         insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
110
111         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
112
113         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
114
115         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
116
117         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
118
119         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
120 }
121
122 #[test]
123 fn test_funding_exceeds_no_wumbo_limit() {
124         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
125         // them.
126         use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
127         let chanmon_cfgs = create_chanmon_cfgs(2);
128         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
129         node_cfgs[1].features = InitFeatures::known().clear_wumbo();
130         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
131         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
132
133         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
134                 Err(APIError::APIMisuseError { err }) => {
135                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
136                 },
137                 _ => panic!()
138         }
139 }
140
141 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
142         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
143         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
144         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
145         // in normal testing, we test it explicitly here.
146         let chanmon_cfgs = create_chanmon_cfgs(2);
147         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
148         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
149         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
150
151         // Have node0 initiate a channel to node1 with aforementioned parameters
152         let mut push_amt = 100_000_000;
153         let feerate_per_kw = 253;
154         let opt_anchors = false;
155         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
156         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
157
158         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();
159         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
160         if !send_from_initiator {
161                 open_channel_message.channel_reserve_satoshis = 0;
162                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
163         }
164         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
165
166         // Extract the channel accept message from node1 to node0
167         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
168         if send_from_initiator {
169                 accept_channel_message.channel_reserve_satoshis = 0;
170                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
171         }
172         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
173         {
174                 let mut lock;
175                 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
176                 chan.holder_selected_channel_reserve_satoshis = 0;
177                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
178         }
179
180         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
181         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
182         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
183
184         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
185         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
186         if send_from_initiator {
187                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
188                         // Note that for outbound channels we have to consider the commitment tx fee and the
189                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
190                         // well as an additional HTLC.
191                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
192         } else {
193                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
194         }
195 }
196
197 #[test]
198 fn test_counterparty_no_reserve() {
199         do_test_counterparty_no_reserve(true);
200         do_test_counterparty_no_reserve(false);
201 }
202
203 #[test]
204 fn test_async_inbound_update_fee() {
205         let chanmon_cfgs = create_chanmon_cfgs(2);
206         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
207         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
208         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
209         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
210
211         // balancing
212         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
213
214         // A                                        B
215         // update_fee                            ->
216         // send (1) commitment_signed            -.
217         //                                       <- update_add_htlc/commitment_signed
218         // send (2) RAA (awaiting remote revoke) -.
219         // (1) commitment_signed is delivered    ->
220         //                                       .- send (3) RAA (awaiting remote revoke)
221         // (2) RAA is delivered                  ->
222         //                                       .- send (4) commitment_signed
223         //                                       <- (3) RAA is delivered
224         // send (5) commitment_signed            -.
225         //                                       <- (4) commitment_signed is delivered
226         // send (6) RAA                          -.
227         // (5) commitment_signed is delivered    ->
228         //                                       <- RAA
229         // (6) RAA is delivered                  ->
230
231         // First nodes[0] generates an update_fee
232         {
233                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
234                 *feerate_lock += 20;
235         }
236         nodes[0].node.timer_tick_occurred();
237         check_added_monitors!(nodes[0], 1);
238
239         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
240         assert_eq!(events_0.len(), 1);
241         let (update_msg, commitment_signed) = match events_0[0] { // (1)
242                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
243                         (update_fee.as_ref(), commitment_signed)
244                 },
245                 _ => panic!("Unexpected event"),
246         };
247
248         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
249
250         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
251         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
252         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
253         check_added_monitors!(nodes[1], 1);
254
255         let payment_event = {
256                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
257                 assert_eq!(events_1.len(), 1);
258                 SendEvent::from_event(events_1.remove(0))
259         };
260         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
261         assert_eq!(payment_event.msgs.len(), 1);
262
263         // ...now when the messages get delivered everyone should be happy
264         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
265         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
266         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
267         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
268         check_added_monitors!(nodes[0], 1);
269
270         // deliver(1), generate (3):
271         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
272         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
273         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
274         check_added_monitors!(nodes[1], 1);
275
276         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
277         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
278         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
279         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
280         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
281         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
282         assert!(bs_update.update_fee.is_none()); // (4)
283         check_added_monitors!(nodes[1], 1);
284
285         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
286         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
287         assert!(as_update.update_add_htlcs.is_empty()); // (5)
288         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
289         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
290         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
291         assert!(as_update.update_fee.is_none()); // (5)
292         check_added_monitors!(nodes[0], 1);
293
294         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
295         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
296         // only (6) so get_event_msg's assert(len == 1) passes
297         check_added_monitors!(nodes[0], 1);
298
299         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
300         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
301         check_added_monitors!(nodes[1], 1);
302
303         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
304         check_added_monitors!(nodes[0], 1);
305
306         let events_2 = nodes[0].node.get_and_clear_pending_events();
307         assert_eq!(events_2.len(), 1);
308         match events_2[0] {
309                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
310                 _ => panic!("Unexpected event"),
311         }
312
313         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
314         check_added_monitors!(nodes[1], 1);
315 }
316
317 #[test]
318 fn test_update_fee_unordered_raa() {
319         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
320         // crash in an earlier version of the update_fee patch)
321         let chanmon_cfgs = create_chanmon_cfgs(2);
322         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
323         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
324         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
325         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
326
327         // balancing
328         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
329
330         // First nodes[0] generates an update_fee
331         {
332                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
333                 *feerate_lock += 20;
334         }
335         nodes[0].node.timer_tick_occurred();
336         check_added_monitors!(nodes[0], 1);
337
338         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
339         assert_eq!(events_0.len(), 1);
340         let update_msg = match events_0[0] { // (1)
341                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
342                         update_fee.as_ref()
343                 },
344                 _ => panic!("Unexpected event"),
345         };
346
347         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
348
349         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
350         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
351         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
352         check_added_monitors!(nodes[1], 1);
353
354         let payment_event = {
355                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
356                 assert_eq!(events_1.len(), 1);
357                 SendEvent::from_event(events_1.remove(0))
358         };
359         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
360         assert_eq!(payment_event.msgs.len(), 1);
361
362         // ...now when the messages get delivered everyone should be happy
363         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
364         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
365         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
366         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
367         check_added_monitors!(nodes[0], 1);
368
369         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
370         check_added_monitors!(nodes[1], 1);
371
372         // We can't continue, sadly, because our (1) now has a bogus signature
373 }
374
375 #[test]
376 fn test_multi_flight_update_fee() {
377         let chanmon_cfgs = create_chanmon_cfgs(2);
378         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
379         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
380         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
381         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
382
383         // A                                        B
384         // update_fee/commitment_signed          ->
385         //                                       .- send (1) RAA and (2) commitment_signed
386         // update_fee (never committed)          ->
387         // (3) update_fee                        ->
388         // We have to manually generate the above update_fee, it is allowed by the protocol but we
389         // don't track which updates correspond to which revoke_and_ack responses so we're in
390         // AwaitingRAA mode and will not generate the update_fee yet.
391         //                                       <- (1) RAA delivered
392         // (3) is generated and send (4) CS      -.
393         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
394         // know the per_commitment_point to use for it.
395         //                                       <- (2) commitment_signed delivered
396         // revoke_and_ack                        ->
397         //                                          B should send no response here
398         // (4) commitment_signed delivered       ->
399         //                                       <- RAA/commitment_signed delivered
400         // revoke_and_ack                        ->
401
402         // First nodes[0] generates an update_fee
403         let initial_feerate;
404         {
405                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
406                 initial_feerate = *feerate_lock;
407                 *feerate_lock = initial_feerate + 20;
408         }
409         nodes[0].node.timer_tick_occurred();
410         check_added_monitors!(nodes[0], 1);
411
412         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
413         assert_eq!(events_0.len(), 1);
414         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
415                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
416                         (update_fee.as_ref().unwrap(), commitment_signed)
417                 },
418                 _ => panic!("Unexpected event"),
419         };
420
421         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
422         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
423         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
424         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
425         check_added_monitors!(nodes[1], 1);
426
427         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
428         // transaction:
429         {
430                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
431                 *feerate_lock = initial_feerate + 40;
432         }
433         nodes[0].node.timer_tick_occurred();
434         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
435         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
436
437         // Create the (3) update_fee message that nodes[0] will generate before it does...
438         let mut update_msg_2 = msgs::UpdateFee {
439                 channel_id: update_msg_1.channel_id.clone(),
440                 feerate_per_kw: (initial_feerate + 30) as u32,
441         };
442
443         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
444
445         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
446         // Deliver (3)
447         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
448
449         // Deliver (1), generating (3) and (4)
450         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
451         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
452         check_added_monitors!(nodes[0], 1);
453         assert!(as_second_update.update_add_htlcs.is_empty());
454         assert!(as_second_update.update_fulfill_htlcs.is_empty());
455         assert!(as_second_update.update_fail_htlcs.is_empty());
456         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
457         // Check that the update_fee newly generated matches what we delivered:
458         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
459         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
460
461         // Deliver (2) commitment_signed
462         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
463         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
464         check_added_monitors!(nodes[0], 1);
465         // No commitment_signed so get_event_msg's assert(len == 1) passes
466
467         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
468         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
469         check_added_monitors!(nodes[1], 1);
470
471         // Delever (4)
472         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
473         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
474         check_added_monitors!(nodes[1], 1);
475
476         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
477         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
478         check_added_monitors!(nodes[0], 1);
479
480         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
481         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
482         // No commitment_signed so get_event_msg's assert(len == 1) passes
483         check_added_monitors!(nodes[0], 1);
484
485         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
486         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
487         check_added_monitors!(nodes[1], 1);
488 }
489
490 fn do_test_sanity_on_in_flight_opens(steps: u8) {
491         // Previously, we had issues deserializing channels when we hadn't connected the first block
492         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
493         // serialization round-trips and simply do steps towards opening a channel and then drop the
494         // Node objects.
495
496         let chanmon_cfgs = create_chanmon_cfgs(2);
497         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
498         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
499         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
500
501         if steps & 0b1000_0000 != 0{
502                 let block = Block {
503                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
504                         txdata: vec![],
505                 };
506                 connect_block(&nodes[0], &block);
507                 connect_block(&nodes[1], &block);
508         }
509
510         if steps & 0x0f == 0 { return; }
511         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
512         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
513
514         if steps & 0x0f == 1 { return; }
515         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
516         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
517
518         if steps & 0x0f == 2 { return; }
519         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
520
521         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
522
523         if steps & 0x0f == 3 { return; }
524         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
525         check_added_monitors!(nodes[0], 0);
526         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
527
528         if steps & 0x0f == 4 { return; }
529         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
530         {
531                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
532                 assert_eq!(added_monitors.len(), 1);
533                 assert_eq!(added_monitors[0].0, funding_output);
534                 added_monitors.clear();
535         }
536         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
537
538         if steps & 0x0f == 5 { return; }
539         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
540         {
541                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
542                 assert_eq!(added_monitors.len(), 1);
543                 assert_eq!(added_monitors[0].0, funding_output);
544                 added_monitors.clear();
545         }
546
547         let events_4 = nodes[0].node.get_and_clear_pending_events();
548         assert_eq!(events_4.len(), 0);
549
550         if steps & 0x0f == 6 { return; }
551         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
552
553         if steps & 0x0f == 7 { return; }
554         confirm_transaction_at(&nodes[0], &tx, 2);
555         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
556         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
557 }
558
559 #[test]
560 fn test_sanity_on_in_flight_opens() {
561         do_test_sanity_on_in_flight_opens(0);
562         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
563         do_test_sanity_on_in_flight_opens(1);
564         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
565         do_test_sanity_on_in_flight_opens(2);
566         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
567         do_test_sanity_on_in_flight_opens(3);
568         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
569         do_test_sanity_on_in_flight_opens(4);
570         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
571         do_test_sanity_on_in_flight_opens(5);
572         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
573         do_test_sanity_on_in_flight_opens(6);
574         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
575         do_test_sanity_on_in_flight_opens(7);
576         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
577         do_test_sanity_on_in_flight_opens(8);
578         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
579 }
580
581 #[test]
582 fn test_update_fee_vanilla() {
583         let chanmon_cfgs = create_chanmon_cfgs(2);
584         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
585         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
586         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
587         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
588
589         {
590                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
591                 *feerate_lock += 25;
592         }
593         nodes[0].node.timer_tick_occurred();
594         check_added_monitors!(nodes[0], 1);
595
596         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
597         assert_eq!(events_0.len(), 1);
598         let (update_msg, commitment_signed) = match events_0[0] {
599                         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 } } => {
600                         (update_fee.as_ref(), commitment_signed)
601                 },
602                 _ => panic!("Unexpected event"),
603         };
604         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
605
606         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
607         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
608         check_added_monitors!(nodes[1], 1);
609
610         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
611         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
612         check_added_monitors!(nodes[0], 1);
613
614         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
615         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
616         // No commitment_signed so get_event_msg's assert(len == 1) passes
617         check_added_monitors!(nodes[0], 1);
618
619         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
620         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
621         check_added_monitors!(nodes[1], 1);
622 }
623
624 #[test]
625 fn test_update_fee_that_funder_cannot_afford() {
626         let chanmon_cfgs = create_chanmon_cfgs(2);
627         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
628         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
629         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
630         let channel_value = 5000;
631         let push_sats = 700;
632         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
633         let channel_id = chan.2;
634         let secp_ctx = Secp256k1::new();
635         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
636
637         let opt_anchors = false;
638
639         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
640         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
641         // calculate two different feerates here - the expected local limit as well as the expected
642         // remote limit.
643         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;
644         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
645         {
646                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
647                 *feerate_lock = feerate;
648         }
649         nodes[0].node.timer_tick_occurred();
650         check_added_monitors!(nodes[0], 1);
651         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
652
653         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
654
655         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
656
657         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
658         {
659                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
660
661                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
662                 assert_eq!(commitment_tx.output.len(), 2);
663                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
664                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
665                 actual_fee = channel_value - actual_fee;
666                 assert_eq!(total_fee, actual_fee);
667         }
668
669         {
670                 // Increment the feerate by a small constant, accounting for rounding errors
671                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
672                 *feerate_lock += 4;
673         }
674         nodes[0].node.timer_tick_occurred();
675         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
676         check_added_monitors!(nodes[0], 0);
677
678         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
679
680         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
681         // needed to sign the new commitment tx and (2) sign the new commitment tx.
682         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
683                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
684                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
685                 let chan_signer = local_chan.get_signer();
686                 let pubkeys = chan_signer.pubkeys();
687                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
688                  pubkeys.funding_pubkey)
689         };
690         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
691                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
692                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
693                 let chan_signer = remote_chan.get_signer();
694                 let pubkeys = chan_signer.pubkeys();
695                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
696                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
697                  pubkeys.funding_pubkey)
698         };
699
700         // Assemble the set of keys we can use for signatures for our commitment_signed message.
701         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
702                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
703
704         let res = {
705                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
706                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
707                 let local_chan_signer = local_chan.get_signer();
708                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
709                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
710                         INITIAL_COMMITMENT_NUMBER - 1,
711                         push_sats,
712                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
713                         opt_anchors, local_funding, remote_funding,
714                         commit_tx_keys.clone(),
715                         non_buffer_feerate + 4,
716                         &mut htlcs,
717                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
718                 );
719                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
720         };
721
722         let commit_signed_msg = msgs::CommitmentSigned {
723                 channel_id: chan.2,
724                 signature: res.0,
725                 htlc_signatures: res.1
726         };
727
728         let update_fee = msgs::UpdateFee {
729                 channel_id: chan.2,
730                 feerate_per_kw: non_buffer_feerate + 4,
731         };
732
733         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
734
735         //While producing the commitment_signed response after handling a received update_fee request the
736         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
737         //Should produce and error.
738         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
739         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
740         check_added_monitors!(nodes[1], 1);
741         check_closed_broadcast!(nodes[1], true);
742         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
743 }
744
745 #[test]
746 fn test_update_fee_with_fundee_update_add_htlc() {
747         let chanmon_cfgs = create_chanmon_cfgs(2);
748         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
749         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
750         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
751         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
752
753         // balancing
754         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
755
756         {
757                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
758                 *feerate_lock += 20;
759         }
760         nodes[0].node.timer_tick_occurred();
761         check_added_monitors!(nodes[0], 1);
762
763         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
764         assert_eq!(events_0.len(), 1);
765         let (update_msg, commitment_signed) = match events_0[0] {
766                         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 } } => {
767                         (update_fee.as_ref(), commitment_signed)
768                 },
769                 _ => panic!("Unexpected event"),
770         };
771         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
772         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
773         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
774         check_added_monitors!(nodes[1], 1);
775
776         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
777
778         // nothing happens since node[1] is in AwaitingRemoteRevoke
779         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
780         {
781                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
782                 assert_eq!(added_monitors.len(), 0);
783                 added_monitors.clear();
784         }
785         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
786         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
787         // node[1] has nothing to do
788
789         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
790         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
791         check_added_monitors!(nodes[0], 1);
792
793         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
794         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
795         // No commitment_signed so get_event_msg's assert(len == 1) passes
796         check_added_monitors!(nodes[0], 1);
797         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
798         check_added_monitors!(nodes[1], 1);
799         // AwaitingRemoteRevoke ends here
800
801         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
802         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
803         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
804         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
805         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
806         assert_eq!(commitment_update.update_fee.is_none(), true);
807
808         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
809         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
810         check_added_monitors!(nodes[0], 1);
811         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
812
813         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
814         check_added_monitors!(nodes[1], 1);
815         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
816
817         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
818         check_added_monitors!(nodes[1], 1);
819         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
820         // No commitment_signed so get_event_msg's assert(len == 1) passes
821
822         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
823         check_added_monitors!(nodes[0], 1);
824         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
825
826         expect_pending_htlcs_forwardable!(nodes[0]);
827
828         let events = nodes[0].node.get_and_clear_pending_events();
829         assert_eq!(events.len(), 1);
830         match events[0] {
831                 Event::PaymentReceived { .. } => { },
832                 _ => panic!("Unexpected event"),
833         };
834
835         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
836
837         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
838         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
839         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
840         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
841         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
842 }
843
844 #[test]
845 fn test_update_fee() {
846         let chanmon_cfgs = create_chanmon_cfgs(2);
847         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
848         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
849         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
850         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
851         let channel_id = chan.2;
852
853         // A                                        B
854         // (1) update_fee/commitment_signed      ->
855         //                                       <- (2) revoke_and_ack
856         //                                       .- send (3) commitment_signed
857         // (4) update_fee/commitment_signed      ->
858         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
859         //                                       <- (3) commitment_signed delivered
860         // send (6) revoke_and_ack               -.
861         //                                       <- (5) deliver revoke_and_ack
862         // (6) deliver revoke_and_ack            ->
863         //                                       .- send (7) commitment_signed in response to (4)
864         //                                       <- (7) deliver commitment_signed
865         // revoke_and_ack                        ->
866
867         // Create and deliver (1)...
868         let feerate;
869         {
870                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
871                 feerate = *feerate_lock;
872                 *feerate_lock = feerate + 20;
873         }
874         nodes[0].node.timer_tick_occurred();
875         check_added_monitors!(nodes[0], 1);
876
877         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
878         assert_eq!(events_0.len(), 1);
879         let (update_msg, commitment_signed) = match events_0[0] {
880                         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 } } => {
881                         (update_fee.as_ref(), commitment_signed)
882                 },
883                 _ => panic!("Unexpected event"),
884         };
885         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
886
887         // Generate (2) and (3):
888         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
889         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
890         check_added_monitors!(nodes[1], 1);
891
892         // Deliver (2):
893         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
894         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
895         check_added_monitors!(nodes[0], 1);
896
897         // Create and deliver (4)...
898         {
899                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
900                 *feerate_lock = feerate + 30;
901         }
902         nodes[0].node.timer_tick_occurred();
903         check_added_monitors!(nodes[0], 1);
904         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
905         assert_eq!(events_0.len(), 1);
906         let (update_msg, commitment_signed) = match events_0[0] {
907                         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 } } => {
908                         (update_fee.as_ref(), commitment_signed)
909                 },
910                 _ => panic!("Unexpected event"),
911         };
912
913         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
914         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
915         check_added_monitors!(nodes[1], 1);
916         // ... creating (5)
917         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
918         // No commitment_signed so get_event_msg's assert(len == 1) passes
919
920         // Handle (3), creating (6):
921         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
922         check_added_monitors!(nodes[0], 1);
923         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
924         // No commitment_signed so get_event_msg's assert(len == 1) passes
925
926         // Deliver (5):
927         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
928         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
929         check_added_monitors!(nodes[0], 1);
930
931         // Deliver (6), creating (7):
932         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
933         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
934         assert!(commitment_update.update_add_htlcs.is_empty());
935         assert!(commitment_update.update_fulfill_htlcs.is_empty());
936         assert!(commitment_update.update_fail_htlcs.is_empty());
937         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
938         assert!(commitment_update.update_fee.is_none());
939         check_added_monitors!(nodes[1], 1);
940
941         // Deliver (7)
942         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
943         check_added_monitors!(nodes[0], 1);
944         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
945         // No commitment_signed so get_event_msg's assert(len == 1) passes
946
947         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
948         check_added_monitors!(nodes[1], 1);
949         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
950
951         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
952         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
953         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
954         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
955         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
956 }
957
958 #[test]
959 fn fake_network_test() {
960         // Simple test which builds a network of ChannelManagers, connects them to each other, and
961         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
962         let chanmon_cfgs = create_chanmon_cfgs(4);
963         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
964         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
965         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
966
967         // Create some initial channels
968         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
969         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
970         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
971
972         // Rebalance the network a bit by relaying one payment through all the channels...
973         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
974         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
975         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
976         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
977
978         // Send some more payments
979         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
980         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
981         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
982
983         // Test failure packets
984         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
985         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
986
987         // Add a new channel that skips 3
988         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
989
990         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
991         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
992         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
993         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
994         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
995         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
996         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
997
998         // Do some rebalance loop payments, simultaneously
999         let mut hops = Vec::with_capacity(3);
1000         hops.push(RouteHop {
1001                 pubkey: nodes[2].node.get_our_node_id(),
1002                 node_features: NodeFeatures::empty(),
1003                 short_channel_id: chan_2.0.contents.short_channel_id,
1004                 channel_features: ChannelFeatures::empty(),
1005                 fee_msat: 0,
1006                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1007         });
1008         hops.push(RouteHop {
1009                 pubkey: nodes[3].node.get_our_node_id(),
1010                 node_features: NodeFeatures::empty(),
1011                 short_channel_id: chan_3.0.contents.short_channel_id,
1012                 channel_features: ChannelFeatures::empty(),
1013                 fee_msat: 0,
1014                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1015         });
1016         hops.push(RouteHop {
1017                 pubkey: nodes[1].node.get_our_node_id(),
1018                 node_features: NodeFeatures::known(),
1019                 short_channel_id: chan_4.0.contents.short_channel_id,
1020                 channel_features: ChannelFeatures::known(),
1021                 fee_msat: 1000000,
1022                 cltv_expiry_delta: TEST_FINAL_CLTV,
1023         });
1024         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;
1025         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;
1026         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;
1027
1028         let mut hops = Vec::with_capacity(3);
1029         hops.push(RouteHop {
1030                 pubkey: nodes[3].node.get_our_node_id(),
1031                 node_features: NodeFeatures::empty(),
1032                 short_channel_id: chan_4.0.contents.short_channel_id,
1033                 channel_features: ChannelFeatures::empty(),
1034                 fee_msat: 0,
1035                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1036         });
1037         hops.push(RouteHop {
1038                 pubkey: nodes[2].node.get_our_node_id(),
1039                 node_features: NodeFeatures::empty(),
1040                 short_channel_id: chan_3.0.contents.short_channel_id,
1041                 channel_features: ChannelFeatures::empty(),
1042                 fee_msat: 0,
1043                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1044         });
1045         hops.push(RouteHop {
1046                 pubkey: nodes[1].node.get_our_node_id(),
1047                 node_features: NodeFeatures::known(),
1048                 short_channel_id: chan_2.0.contents.short_channel_id,
1049                 channel_features: ChannelFeatures::known(),
1050                 fee_msat: 1000000,
1051                 cltv_expiry_delta: TEST_FINAL_CLTV,
1052         });
1053         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;
1054         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;
1055         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;
1056
1057         // Claim the rebalances...
1058         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1059         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1060
1061         // Add a duplicate new channel from 2 to 4
1062         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1063
1064         // Send some payments across both channels
1065         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1066         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1067         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1068
1069
1070         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1071         let events = nodes[0].node.get_and_clear_pending_msg_events();
1072         assert_eq!(events.len(), 0);
1073         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);
1074
1075         //TODO: Test that routes work again here as we've been notified that the channel is full
1076
1077         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1078         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1079         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1080
1081         // Close down the channels...
1082         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1083         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1084         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1085         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1086         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1087         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1088         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1089         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1090         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1091         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1092         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1093         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1094         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1095         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1096         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1097 }
1098
1099 #[test]
1100 fn holding_cell_htlc_counting() {
1101         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1102         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1103         // commitment dance rounds.
1104         let chanmon_cfgs = create_chanmon_cfgs(3);
1105         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1106         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1107         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1108         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1109         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1110
1111         let mut payments = Vec::new();
1112         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1113                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1114                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1115                 payments.push((payment_preimage, payment_hash));
1116         }
1117         check_added_monitors!(nodes[1], 1);
1118
1119         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1120         assert_eq!(events.len(), 1);
1121         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1122         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1123
1124         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1125         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1126         // another HTLC.
1127         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1128         {
1129                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1130                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1131                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1132                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1133         }
1134
1135         // This should also be true if we try to forward a payment.
1136         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1137         {
1138                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1139                 check_added_monitors!(nodes[0], 1);
1140         }
1141
1142         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1143         assert_eq!(events.len(), 1);
1144         let payment_event = SendEvent::from_event(events.pop().unwrap());
1145         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1146
1147         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1148         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1149         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1150         // fails), the second will process the resulting failure and fail the HTLC backward.
1151         expect_pending_htlcs_forwardable!(nodes[1]);
1152         expect_pending_htlcs_forwardable!(nodes[1]);
1153         check_added_monitors!(nodes[1], 1);
1154
1155         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1156         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1157         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1158
1159         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1160
1161         // Now forward all the pending HTLCs and claim them back
1162         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1163         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1164         check_added_monitors!(nodes[2], 1);
1165
1166         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1167         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1168         check_added_monitors!(nodes[1], 1);
1169         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1170
1171         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1172         check_added_monitors!(nodes[1], 1);
1173         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1174
1175         for ref update in as_updates.update_add_htlcs.iter() {
1176                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1177         }
1178         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1179         check_added_monitors!(nodes[2], 1);
1180         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1181         check_added_monitors!(nodes[2], 1);
1182         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1183
1184         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1185         check_added_monitors!(nodes[1], 1);
1186         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1187         check_added_monitors!(nodes[1], 1);
1188         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1189
1190         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1191         check_added_monitors!(nodes[2], 1);
1192
1193         expect_pending_htlcs_forwardable!(nodes[2]);
1194
1195         let events = nodes[2].node.get_and_clear_pending_events();
1196         assert_eq!(events.len(), payments.len());
1197         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1198                 match event {
1199                         &Event::PaymentReceived { ref payment_hash, .. } => {
1200                                 assert_eq!(*payment_hash, *hash);
1201                         },
1202                         _ => panic!("Unexpected event"),
1203                 };
1204         }
1205
1206         for (preimage, _) in payments.drain(..) {
1207                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1208         }
1209
1210         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1211 }
1212
1213 #[test]
1214 fn duplicate_htlc_test() {
1215         // Test that we accept duplicate payment_hash HTLCs across the network and that
1216         // claiming/failing them are all separate and don't affect each other
1217         let chanmon_cfgs = create_chanmon_cfgs(6);
1218         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1219         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1220         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1221
1222         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1223         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1224         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1225         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1226         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1227         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1228
1229         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1230
1231         *nodes[0].network_payment_count.borrow_mut() -= 1;
1232         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1233
1234         *nodes[0].network_payment_count.borrow_mut() -= 1;
1235         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1236
1237         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1238         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1239         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1240 }
1241
1242 #[test]
1243 fn test_duplicate_htlc_different_direction_onchain() {
1244         // Test that ChannelMonitor doesn't generate 2 preimage txn
1245         // when we have 2 HTLCs with same preimage that go across a node
1246         // in opposite directions, even with the same payment secret.
1247         let chanmon_cfgs = create_chanmon_cfgs(2);
1248         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1249         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1250         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1251
1252         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1253
1254         // balancing
1255         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1256
1257         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1258
1259         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1260         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1261         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1262
1263         // Provide preimage to node 0 by claiming payment
1264         nodes[0].node.claim_funds(payment_preimage);
1265         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1266         check_added_monitors!(nodes[0], 1);
1267
1268         // Broadcast node 1 commitment txn
1269         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1270
1271         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1272         let mut has_both_htlcs = 0; // check htlcs match ones committed
1273         for outp in remote_txn[0].output.iter() {
1274                 if outp.value == 800_000 / 1000 {
1275                         has_both_htlcs += 1;
1276                 } else if outp.value == 900_000 / 1000 {
1277                         has_both_htlcs += 1;
1278                 }
1279         }
1280         assert_eq!(has_both_htlcs, 2);
1281
1282         mine_transaction(&nodes[0], &remote_txn[0]);
1283         check_added_monitors!(nodes[0], 1);
1284         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1285         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1286
1287         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1288         assert_eq!(claim_txn.len(), 8);
1289
1290         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1291
1292         check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1293         check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1294
1295         let bump_tx = if claim_txn[1] == claim_txn[4] {
1296                 assert_eq!(claim_txn[1], claim_txn[4]);
1297                 assert_eq!(claim_txn[2], claim_txn[5]);
1298
1299                 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1300
1301                 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1302                 &claim_txn[3]
1303         } else {
1304                 assert_eq!(claim_txn[1], claim_txn[3]);
1305                 assert_eq!(claim_txn[2], claim_txn[4]);
1306
1307                 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1308
1309                 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1310
1311                 &claim_txn[7]
1312         };
1313
1314         assert_eq!(claim_txn[0].input.len(), 1);
1315         assert_eq!(bump_tx.input.len(), 1);
1316         assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1317
1318         assert_eq!(claim_txn[0].input.len(), 1);
1319         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1320         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1321
1322         assert_eq!(claim_txn[6].input.len(), 1);
1323         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1324         check_spends!(claim_txn[6], remote_txn[0]);
1325         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1326
1327         let events = nodes[0].node.get_and_clear_pending_msg_events();
1328         assert_eq!(events.len(), 3);
1329         for e in events {
1330                 match e {
1331                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1332                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1333                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1334                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1335                         },
1336                         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, .. } } => {
1337                                 assert!(update_add_htlcs.is_empty());
1338                                 assert!(update_fail_htlcs.is_empty());
1339                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1340                                 assert!(update_fail_malformed_htlcs.is_empty());
1341                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1342                         },
1343                         _ => panic!("Unexpected event"),
1344                 }
1345         }
1346 }
1347
1348 #[test]
1349 fn test_basic_channel_reserve() {
1350         let chanmon_cfgs = create_chanmon_cfgs(2);
1351         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1352         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1353         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1354         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1355
1356         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1357         let channel_reserve = chan_stat.channel_reserve_msat;
1358
1359         // The 2* and +1 are for the fee spike reserve.
1360         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1361         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1362         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1363         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1364         match err {
1365                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1366                         match &fails[0] {
1367                                 &APIError::ChannelUnavailable{ref err} =>
1368                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1369                                 _ => panic!("Unexpected error variant"),
1370                         }
1371                 },
1372                 _ => panic!("Unexpected error variant"),
1373         }
1374         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1375         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);
1376
1377         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1378 }
1379
1380 #[test]
1381 fn test_fee_spike_violation_fails_htlc() {
1382         let chanmon_cfgs = create_chanmon_cfgs(2);
1383         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1384         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1385         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1386         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1387
1388         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1389         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1390         let secp_ctx = Secp256k1::new();
1391         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1392
1393         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1394
1395         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1396         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1397         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1398         let msg = msgs::UpdateAddHTLC {
1399                 channel_id: chan.2,
1400                 htlc_id: 0,
1401                 amount_msat: htlc_msat,
1402                 payment_hash: payment_hash,
1403                 cltv_expiry: htlc_cltv,
1404                 onion_routing_packet: onion_packet,
1405         };
1406
1407         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1408
1409         // Now manually create the commitment_signed message corresponding to the update_add
1410         // nodes[0] just sent. In the code for construction of this message, "local" refers
1411         // to the sender of the message, and "remote" refers to the receiver.
1412
1413         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1414
1415         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1416
1417         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1418         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1419         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1420                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1421                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1422                 let chan_signer = local_chan.get_signer();
1423                 // Make the signer believe we validated another commitment, so we can release the secret
1424                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1425
1426                 let pubkeys = chan_signer.pubkeys();
1427                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1428                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1429                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1430                  chan_signer.pubkeys().funding_pubkey)
1431         };
1432         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1433                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1434                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1435                 let chan_signer = remote_chan.get_signer();
1436                 let pubkeys = chan_signer.pubkeys();
1437                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1438                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1439                  chan_signer.pubkeys().funding_pubkey)
1440         };
1441
1442         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1443         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1444                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1445
1446         // Build the remote commitment transaction so we can sign it, and then later use the
1447         // signature for the commitment_signed message.
1448         let local_chan_balance = 1313;
1449
1450         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1451                 offered: false,
1452                 amount_msat: 3460001,
1453                 cltv_expiry: htlc_cltv,
1454                 payment_hash,
1455                 transaction_output_index: Some(1),
1456         };
1457
1458         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1459
1460         let res = {
1461                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1462                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1463                 let local_chan_signer = local_chan.get_signer();
1464                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1465                         commitment_number,
1466                         95000,
1467                         local_chan_balance,
1468                         local_chan.opt_anchors(), local_funding, remote_funding,
1469                         commit_tx_keys.clone(),
1470                         feerate_per_kw,
1471                         &mut vec![(accepted_htlc_info, ())],
1472                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1473                 );
1474                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1475         };
1476
1477         let commit_signed_msg = msgs::CommitmentSigned {
1478                 channel_id: chan.2,
1479                 signature: res.0,
1480                 htlc_signatures: res.1
1481         };
1482
1483         // Send the commitment_signed message to the nodes[1].
1484         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1485         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1486
1487         // Send the RAA to nodes[1].
1488         let raa_msg = msgs::RevokeAndACK {
1489                 channel_id: chan.2,
1490                 per_commitment_secret: local_secret,
1491                 next_per_commitment_point: next_local_point
1492         };
1493         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1494
1495         let events = nodes[1].node.get_and_clear_pending_msg_events();
1496         assert_eq!(events.len(), 1);
1497         // Make sure the HTLC failed in the way we expect.
1498         match events[0] {
1499                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1500                         assert_eq!(update_fail_htlcs.len(), 1);
1501                         update_fail_htlcs[0].clone()
1502                 },
1503                 _ => panic!("Unexpected event"),
1504         };
1505         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1506                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1507
1508         check_added_monitors!(nodes[1], 2);
1509 }
1510
1511 #[test]
1512 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1513         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1514         // Set the fee rate for the channel very high, to the point where the fundee
1515         // sending any above-dust amount would result in a channel reserve violation.
1516         // In this test we check that we would be prevented from sending an HTLC in
1517         // this situation.
1518         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1519         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1520         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1521         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1522
1523         let opt_anchors = false;
1524
1525         let mut push_amt = 100_000_000;
1526         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1527         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1528
1529         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1530
1531         // Sending exactly enough to hit the reserve amount should be accepted
1532         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1533                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1534         }
1535
1536         // However one more HTLC should be significantly over the reserve amount and fail.
1537         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1538         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1539                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1540         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1541         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);
1542 }
1543
1544 #[test]
1545 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1546         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1547         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1548         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1549         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1550         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1551
1552         let opt_anchors = false;
1553
1554         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1555         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1556         // transaction fee with 0 HTLCs (183 sats)).
1557         let mut push_amt = 100_000_000;
1558         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1559         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1560         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1561
1562         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1563         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1564                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1565         }
1566
1567         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1568         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1569         let secp_ctx = Secp256k1::new();
1570         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1571         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1572         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1573         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1574         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1575         let msg = msgs::UpdateAddHTLC {
1576                 channel_id: chan.2,
1577                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1578                 amount_msat: htlc_msat,
1579                 payment_hash: payment_hash,
1580                 cltv_expiry: htlc_cltv,
1581                 onion_routing_packet: onion_packet,
1582         };
1583
1584         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1585         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1586         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);
1587         assert_eq!(nodes[0].node.list_channels().len(), 0);
1588         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1589         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1590         check_added_monitors!(nodes[0], 1);
1591         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() });
1592 }
1593
1594 #[test]
1595 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1596         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1597         // calculating our commitment transaction fee (this was previously broken).
1598         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1599         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1600
1601         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1602         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1603         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1604
1605         let opt_anchors = false;
1606
1607         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1608         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1609         // transaction fee with 0 HTLCs (183 sats)).
1610         let mut push_amt = 100_000_000;
1611         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1612         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1613         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1614
1615         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1616                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1617         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1618         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1619         // commitment transaction fee.
1620         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1621
1622         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1623         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1624                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1625         }
1626
1627         // One more than the dust amt should fail, however.
1628         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1629         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1630                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1631 }
1632
1633 #[test]
1634 fn test_chan_init_feerate_unaffordability() {
1635         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1636         // channel reserve and feerate requirements.
1637         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1638         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1639         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1640         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1641         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1642
1643         let opt_anchors = false;
1644
1645         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1646         // HTLC.
1647         let mut push_amt = 100_000_000;
1648         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1649         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1650                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1651
1652         // During open, we don't have a "counterparty channel reserve" to check against, so that
1653         // requirement only comes into play on the open_channel handling side.
1654         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1655         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1656         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1657         open_channel_msg.push_msat += 1;
1658         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1659
1660         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1661         assert_eq!(msg_events.len(), 1);
1662         match msg_events[0] {
1663                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1664                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1665                 },
1666                 _ => panic!("Unexpected event"),
1667         }
1668 }
1669
1670 #[test]
1671 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1672         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1673         // calculating our counterparty's commitment transaction fee (this was previously broken).
1674         let chanmon_cfgs = create_chanmon_cfgs(2);
1675         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1676         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1677         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1678         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1679
1680         let payment_amt = 46000; // Dust amount
1681         // In the previous code, these first four payments would succeed.
1682         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1683         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1684         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1686
1687         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1688         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1690         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1691         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1693
1694         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1695         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1696         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1697         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1698 }
1699
1700 #[test]
1701 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1702         let chanmon_cfgs = create_chanmon_cfgs(3);
1703         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1704         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1705         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1706         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1707         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1708
1709         let feemsat = 239;
1710         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1711         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1712         let feerate = get_feerate!(nodes[0], chan.2);
1713         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1714
1715         // Add a 2* and +1 for the fee spike reserve.
1716         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1717         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;
1718         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1719
1720         // Add a pending HTLC.
1721         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1722         let payment_event_1 = {
1723                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1724                 check_added_monitors!(nodes[0], 1);
1725
1726                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1727                 assert_eq!(events.len(), 1);
1728                 SendEvent::from_event(events.remove(0))
1729         };
1730         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1731
1732         // Attempt to trigger a channel reserve violation --> payment failure.
1733         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1734         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;
1735         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1736         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1737
1738         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1739         let secp_ctx = Secp256k1::new();
1740         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1741         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1742         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1743         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1744         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1745         let msg = msgs::UpdateAddHTLC {
1746                 channel_id: chan.2,
1747                 htlc_id: 1,
1748                 amount_msat: htlc_msat + 1,
1749                 payment_hash: our_payment_hash_1,
1750                 cltv_expiry: htlc_cltv,
1751                 onion_routing_packet: onion_packet,
1752         };
1753
1754         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1755         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1756         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1757         assert_eq!(nodes[1].node.list_channels().len(), 1);
1758         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1759         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1760         check_added_monitors!(nodes[1], 1);
1761         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1762 }
1763
1764 #[test]
1765 fn test_inbound_outbound_capacity_is_not_zero() {
1766         let chanmon_cfgs = create_chanmon_cfgs(2);
1767         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1768         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1769         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1770         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1771         let channels0 = node_chanmgrs[0].list_channels();
1772         let channels1 = node_chanmgrs[1].list_channels();
1773         assert_eq!(channels0.len(), 1);
1774         assert_eq!(channels1.len(), 1);
1775
1776         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1777         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1778         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1779
1780         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1781         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1782 }
1783
1784 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1785         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1786 }
1787
1788 #[test]
1789 fn test_channel_reserve_holding_cell_htlcs() {
1790         let chanmon_cfgs = create_chanmon_cfgs(3);
1791         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1792         // When this test was written, the default base fee floated based on the HTLC count.
1793         // It is now fixed, so we simply set the fee to the expected value here.
1794         let mut config = test_default_channel_config();
1795         config.channel_config.forwarding_fee_base_msat = 239;
1796         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1797         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1798         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1799         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1800
1801         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1802         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1803
1804         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1805         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1806
1807         macro_rules! expect_forward {
1808                 ($node: expr) => {{
1809                         let mut events = $node.node.get_and_clear_pending_msg_events();
1810                         assert_eq!(events.len(), 1);
1811                         check_added_monitors!($node, 1);
1812                         let payment_event = SendEvent::from_event(events.remove(0));
1813                         payment_event
1814                 }}
1815         }
1816
1817         let feemsat = 239; // set above
1818         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1819         let feerate = get_feerate!(nodes[0], chan_1.2);
1820         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1821
1822         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1823
1824         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1825         {
1826                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1827                         .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1828                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0, TEST_FINAL_CLTV);
1829                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1830                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1831
1832                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1833                         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)));
1834                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1835                 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);
1836         }
1837
1838         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1839         // nodes[0]'s wealth
1840         loop {
1841                 let amt_msat = recv_value_0 + total_fee_msat;
1842                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1843                 // Also, ensure that each payment has enough to be over the dust limit to
1844                 // ensure it'll be included in each commit tx fee calculation.
1845                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1846                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1847                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1848                         break;
1849                 }
1850
1851                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1852                         .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1853                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1854                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1855                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1856
1857                 let (stat01_, stat11_, stat12_, stat22_) = (
1858                         get_channel_value_stat!(nodes[0], chan_1.2),
1859                         get_channel_value_stat!(nodes[1], chan_1.2),
1860                         get_channel_value_stat!(nodes[1], chan_2.2),
1861                         get_channel_value_stat!(nodes[2], chan_2.2),
1862                 );
1863
1864                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1865                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1866                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1867                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1868                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1869         }
1870
1871         // adding pending output.
1872         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1873         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1874         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1875         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1876         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1877         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1878         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1879         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1880         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1881         // policy.
1882         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1883         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1884         let amt_msat_1 = recv_value_1 + total_fee_msat;
1885
1886         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);
1887         let payment_event_1 = {
1888                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1889                 check_added_monitors!(nodes[0], 1);
1890
1891                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1892                 assert_eq!(events.len(), 1);
1893                 SendEvent::from_event(events.remove(0))
1894         };
1895         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1896
1897         // channel reserve test with htlc pending output > 0
1898         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1899         {
1900                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1901                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1902                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1903                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1904         }
1905
1906         // split the rest to test holding cell
1907         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1908         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1909         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1910         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1911         {
1912                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1913                 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);
1914         }
1915
1916         // now see if they go through on both sides
1917         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);
1918         // but this will stuck in the holding cell
1919         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1920         check_added_monitors!(nodes[0], 0);
1921         let events = nodes[0].node.get_and_clear_pending_events();
1922         assert_eq!(events.len(), 0);
1923
1924         // test with outbound holding cell amount > 0
1925         {
1926                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1927                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1928                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1929                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1930                 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);
1931         }
1932
1933         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);
1934         // this will also stuck in the holding cell
1935         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1936         check_added_monitors!(nodes[0], 0);
1937         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1938         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1939
1940         // flush the pending htlc
1941         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1942         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1943         check_added_monitors!(nodes[1], 1);
1944
1945         // the pending htlc should be promoted to committed
1946         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1947         check_added_monitors!(nodes[0], 1);
1948         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1949
1950         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1951         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1952         // No commitment_signed so get_event_msg's assert(len == 1) passes
1953         check_added_monitors!(nodes[0], 1);
1954
1955         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1956         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1957         check_added_monitors!(nodes[1], 1);
1958
1959         expect_pending_htlcs_forwardable!(nodes[1]);
1960
1961         let ref payment_event_11 = expect_forward!(nodes[1]);
1962         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1963         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1964
1965         expect_pending_htlcs_forwardable!(nodes[2]);
1966         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1967
1968         // flush the htlcs in the holding cell
1969         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1970         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1971         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1972         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1973         expect_pending_htlcs_forwardable!(nodes[1]);
1974
1975         let ref payment_event_3 = expect_forward!(nodes[1]);
1976         assert_eq!(payment_event_3.msgs.len(), 2);
1977         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1978         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1979
1980         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1981         expect_pending_htlcs_forwardable!(nodes[2]);
1982
1983         let events = nodes[2].node.get_and_clear_pending_events();
1984         assert_eq!(events.len(), 2);
1985         match events[0] {
1986                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1987                         assert_eq!(our_payment_hash_21, *payment_hash);
1988                         assert_eq!(recv_value_21, amount_msat);
1989                         match &purpose {
1990                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1991                                         assert!(payment_preimage.is_none());
1992                                         assert_eq!(our_payment_secret_21, *payment_secret);
1993                                 },
1994                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1995                         }
1996                 },
1997                 _ => panic!("Unexpected event"),
1998         }
1999         match events[1] {
2000                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
2001                         assert_eq!(our_payment_hash_22, *payment_hash);
2002                         assert_eq!(recv_value_22, amount_msat);
2003                         match &purpose {
2004                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2005                                         assert!(payment_preimage.is_none());
2006                                         assert_eq!(our_payment_secret_22, *payment_secret);
2007                                 },
2008                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2009                         }
2010                 },
2011                 _ => panic!("Unexpected event"),
2012         }
2013
2014         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2015         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2016         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2017
2018         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2019         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2020         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2021
2022         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2023         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);
2024         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2025         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2026         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2027
2028         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2029         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2030 }
2031
2032 #[test]
2033 fn channel_reserve_in_flight_removes() {
2034         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2035         // can send to its counterparty, but due to update ordering, the other side may not yet have
2036         // considered those HTLCs fully removed.
2037         // This tests that we don't count HTLCs which will not be included in the next remote
2038         // commitment transaction towards the reserve value (as it implies no commitment transaction
2039         // will be generated which violates the remote reserve value).
2040         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2041         // To test this we:
2042         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2043         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2044         //    you only consider the value of the first HTLC, it may not),
2045         //  * start routing a third HTLC from A to B,
2046         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2047         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2048         //  * deliver the first fulfill from B
2049         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2050         //    claim,
2051         //  * deliver A's response CS and RAA.
2052         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2053         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2054         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2055         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2056         let chanmon_cfgs = create_chanmon_cfgs(2);
2057         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2058         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2059         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2060         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2061
2062         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2063         // Route the first two HTLCs.
2064         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2065         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2066         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2067
2068         // Start routing the third HTLC (this is just used to get everyone in the right state).
2069         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2070         let send_1 = {
2071                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2072                 check_added_monitors!(nodes[0], 1);
2073                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2074                 assert_eq!(events.len(), 1);
2075                 SendEvent::from_event(events.remove(0))
2076         };
2077
2078         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2079         // initial fulfill/CS.
2080         nodes[1].node.claim_funds(payment_preimage_1);
2081         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2082         check_added_monitors!(nodes[1], 1);
2083         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2084
2085         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2086         // remove the second HTLC when we send the HTLC back from B to A.
2087         nodes[1].node.claim_funds(payment_preimage_2);
2088         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2089         check_added_monitors!(nodes[1], 1);
2090         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2091
2092         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2093         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2094         check_added_monitors!(nodes[0], 1);
2095         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2096         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2097
2098         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2099         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2100         check_added_monitors!(nodes[1], 1);
2101         // B is already AwaitingRAA, so cant generate a CS here
2102         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2103
2104         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2105         check_added_monitors!(nodes[1], 1);
2106         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2107
2108         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2109         check_added_monitors!(nodes[0], 1);
2110         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2111
2112         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2113         check_added_monitors!(nodes[1], 1);
2114         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2115
2116         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2117         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2118         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2119         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2120         // on-chain as necessary).
2121         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2122         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2123         check_added_monitors!(nodes[0], 1);
2124         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2125         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2126
2127         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2128         check_added_monitors!(nodes[1], 1);
2129         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2130
2131         expect_pending_htlcs_forwardable!(nodes[1]);
2132         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2133
2134         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2135         // resolve the second HTLC from A's point of view.
2136         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2137         check_added_monitors!(nodes[0], 1);
2138         expect_payment_path_successful!(nodes[0]);
2139         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2140
2141         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2142         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2143         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2144         let send_2 = {
2145                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2146                 check_added_monitors!(nodes[1], 1);
2147                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2148                 assert_eq!(events.len(), 1);
2149                 SendEvent::from_event(events.remove(0))
2150         };
2151
2152         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2153         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2154         check_added_monitors!(nodes[0], 1);
2155         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2156
2157         // Now just resolve all the outstanding messages/HTLCs for completeness...
2158
2159         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2160         check_added_monitors!(nodes[1], 1);
2161         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2162
2163         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2164         check_added_monitors!(nodes[1], 1);
2165
2166         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2167         check_added_monitors!(nodes[0], 1);
2168         expect_payment_path_successful!(nodes[0]);
2169         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2170
2171         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2172         check_added_monitors!(nodes[1], 1);
2173         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2174
2175         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2176         check_added_monitors!(nodes[0], 1);
2177
2178         expect_pending_htlcs_forwardable!(nodes[0]);
2179         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2180
2181         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2182         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2183 }
2184
2185 #[test]
2186 fn channel_monitor_network_test() {
2187         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2188         // tests that ChannelMonitor is able to recover from various states.
2189         let chanmon_cfgs = create_chanmon_cfgs(5);
2190         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2191         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2192         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2193
2194         // Create some initial channels
2195         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2196         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2197         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2198         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2199
2200         // Make sure all nodes are at the same starting height
2201         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2202         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2203         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2204         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2205         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2206
2207         // Rebalance the network a bit by relaying one payment through all the channels...
2208         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2209         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2210         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2211         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2212
2213         // Simple case with no pending HTLCs:
2214         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2215         check_added_monitors!(nodes[1], 1);
2216         check_closed_broadcast!(nodes[1], true);
2217         {
2218                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2219                 assert_eq!(node_txn.len(), 1);
2220                 mine_transaction(&nodes[0], &node_txn[0]);
2221                 check_added_monitors!(nodes[0], 1);
2222                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2223         }
2224         check_closed_broadcast!(nodes[0], true);
2225         assert_eq!(nodes[0].node.list_channels().len(), 0);
2226         assert_eq!(nodes[1].node.list_channels().len(), 1);
2227         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2228         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2229
2230         // One pending HTLC is discarded by the force-close:
2231         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2232
2233         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2234         // broadcasted until we reach the timelock time).
2235         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2236         check_closed_broadcast!(nodes[1], true);
2237         check_added_monitors!(nodes[1], 1);
2238         {
2239                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2240                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2241                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2242                 mine_transaction(&nodes[2], &node_txn[0]);
2243                 check_added_monitors!(nodes[2], 1);
2244                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2245         }
2246         check_closed_broadcast!(nodes[2], true);
2247         assert_eq!(nodes[1].node.list_channels().len(), 0);
2248         assert_eq!(nodes[2].node.list_channels().len(), 1);
2249         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2250         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2251
2252         macro_rules! claim_funds {
2253                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2254                         {
2255                                 $node.node.claim_funds($preimage);
2256                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2257                                 check_added_monitors!($node, 1);
2258
2259                                 let events = $node.node.get_and_clear_pending_msg_events();
2260                                 assert_eq!(events.len(), 1);
2261                                 match events[0] {
2262                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2263                                                 assert!(update_add_htlcs.is_empty());
2264                                                 assert!(update_fail_htlcs.is_empty());
2265                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2266                                         },
2267                                         _ => panic!("Unexpected event"),
2268                                 };
2269                         }
2270                 }
2271         }
2272
2273         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2274         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2275         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2276         check_added_monitors!(nodes[2], 1);
2277         check_closed_broadcast!(nodes[2], true);
2278         let node2_commitment_txid;
2279         {
2280                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2281                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2282                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2283                 node2_commitment_txid = node_txn[0].txid();
2284
2285                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2286                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2287                 mine_transaction(&nodes[3], &node_txn[0]);
2288                 check_added_monitors!(nodes[3], 1);
2289                 check_preimage_claim(&nodes[3], &node_txn);
2290         }
2291         check_closed_broadcast!(nodes[3], true);
2292         assert_eq!(nodes[2].node.list_channels().len(), 0);
2293         assert_eq!(nodes[3].node.list_channels().len(), 1);
2294         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2295         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2296
2297         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2298         // confusing us in the following tests.
2299         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2300
2301         // One pending HTLC to time out:
2302         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2303         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2304         // buffer space).
2305
2306         let (close_chan_update_1, close_chan_update_2) = {
2307                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2308                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2309                 assert_eq!(events.len(), 2);
2310                 let close_chan_update_1 = match events[0] {
2311                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2312                                 msg.clone()
2313                         },
2314                         _ => panic!("Unexpected event"),
2315                 };
2316                 match events[1] {
2317                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2318                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2319                         },
2320                         _ => panic!("Unexpected event"),
2321                 }
2322                 check_added_monitors!(nodes[3], 1);
2323
2324                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2325                 {
2326                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2327                         node_txn.retain(|tx| {
2328                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2329                                         false
2330                                 } else { true }
2331                         });
2332                 }
2333
2334                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2335
2336                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2337                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2338
2339                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2340                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2341                 assert_eq!(events.len(), 2);
2342                 let close_chan_update_2 = match events[0] {
2343                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2344                                 msg.clone()
2345                         },
2346                         _ => panic!("Unexpected event"),
2347                 };
2348                 match events[1] {
2349                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2350                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2351                         },
2352                         _ => panic!("Unexpected event"),
2353                 }
2354                 check_added_monitors!(nodes[4], 1);
2355                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2356
2357                 mine_transaction(&nodes[4], &node_txn[0]);
2358                 check_preimage_claim(&nodes[4], &node_txn);
2359                 (close_chan_update_1, close_chan_update_2)
2360         };
2361         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2362         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2363         assert_eq!(nodes[3].node.list_channels().len(), 0);
2364         assert_eq!(nodes[4].node.list_channels().len(), 0);
2365
2366         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2367         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2368         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2369 }
2370
2371 #[test]
2372 fn test_justice_tx() {
2373         // Test justice txn built on revoked HTLC-Success tx, against both sides
2374         let mut alice_config = UserConfig::default();
2375         alice_config.channel_handshake_config.announced_channel = true;
2376         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2377         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2378         let mut bob_config = UserConfig::default();
2379         bob_config.channel_handshake_config.announced_channel = true;
2380         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2381         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2382         let user_cfgs = [Some(alice_config), Some(bob_config)];
2383         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2384         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2385         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2386         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2387         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2388         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2389         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2390         // Create some new channels:
2391         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2392
2393         // A pending HTLC which will be revoked:
2394         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2395         // Get the will-be-revoked local txn from nodes[0]
2396         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2397         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2398         assert_eq!(revoked_local_txn[0].input.len(), 1);
2399         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2400         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2401         assert_eq!(revoked_local_txn[1].input.len(), 1);
2402         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2403         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2404         // Revoke the old state
2405         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2406
2407         {
2408                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2409                 {
2410                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2411                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2412                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2413
2414                         check_spends!(node_txn[0], revoked_local_txn[0]);
2415                         node_txn.swap_remove(0);
2416                         node_txn.truncate(1);
2417                 }
2418                 check_added_monitors!(nodes[1], 1);
2419                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2420                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2421
2422                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2423                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2424                 // Verify broadcast of revoked HTLC-timeout
2425                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2426                 check_added_monitors!(nodes[0], 1);
2427                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2428                 // Broadcast revoked HTLC-timeout on node 1
2429                 mine_transaction(&nodes[1], &node_txn[1]);
2430                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2431         }
2432         get_announce_close_broadcast_events(&nodes, 0, 1);
2433
2434         assert_eq!(nodes[0].node.list_channels().len(), 0);
2435         assert_eq!(nodes[1].node.list_channels().len(), 0);
2436
2437         // We test justice_tx build by A on B's revoked HTLC-Success tx
2438         // Create some new channels:
2439         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2440         {
2441                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2442                 node_txn.clear();
2443         }
2444
2445         // A pending HTLC which will be revoked:
2446         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2447         // Get the will-be-revoked local txn from B
2448         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2449         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2450         assert_eq!(revoked_local_txn[0].input.len(), 1);
2451         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2452         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2453         // Revoke the old state
2454         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2455         {
2456                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2457                 {
2458                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2459                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2460                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2461
2462                         check_spends!(node_txn[0], revoked_local_txn[0]);
2463                         node_txn.swap_remove(0);
2464                 }
2465                 check_added_monitors!(nodes[0], 1);
2466                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2467
2468                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2469                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2470                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2471                 check_added_monitors!(nodes[1], 1);
2472                 mine_transaction(&nodes[0], &node_txn[1]);
2473                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2474                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2475         }
2476         get_announce_close_broadcast_events(&nodes, 0, 1);
2477         assert_eq!(nodes[0].node.list_channels().len(), 0);
2478         assert_eq!(nodes[1].node.list_channels().len(), 0);
2479 }
2480
2481 #[test]
2482 fn revoked_output_claim() {
2483         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2484         // transaction is broadcast by its counterparty
2485         let chanmon_cfgs = create_chanmon_cfgs(2);
2486         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2487         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2488         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2489         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2490         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2491         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2492         assert_eq!(revoked_local_txn.len(), 1);
2493         // Only output is the full channel value back to nodes[0]:
2494         assert_eq!(revoked_local_txn[0].output.len(), 1);
2495         // Send a payment through, updating everyone's latest commitment txn
2496         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2497
2498         // Inform nodes[1] that nodes[0] broadcast a stale tx
2499         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2500         check_added_monitors!(nodes[1], 1);
2501         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2502         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2503         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2504
2505         check_spends!(node_txn[0], revoked_local_txn[0]);
2506         check_spends!(node_txn[1], chan_1.3);
2507
2508         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2509         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2510         get_announce_close_broadcast_events(&nodes, 0, 1);
2511         check_added_monitors!(nodes[0], 1);
2512         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2513 }
2514
2515 #[test]
2516 fn claim_htlc_outputs_shared_tx() {
2517         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2518         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2519         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2520         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2521         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2522         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2523
2524         // Create some new channel:
2525         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2526
2527         // Rebalance the network to generate htlc in the two directions
2528         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2529         // 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
2530         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2531         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2532
2533         // Get the will-be-revoked local txn from node[0]
2534         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2535         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2536         assert_eq!(revoked_local_txn[0].input.len(), 1);
2537         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2538         assert_eq!(revoked_local_txn[1].input.len(), 1);
2539         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2540         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2541         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2542
2543         //Revoke the old state
2544         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2545
2546         {
2547                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2548                 check_added_monitors!(nodes[0], 1);
2549                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2550                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2551                 check_added_monitors!(nodes[1], 1);
2552                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2553                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2554                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2555
2556                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2557                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2558
2559                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2560                 check_spends!(node_txn[0], revoked_local_txn[0]);
2561
2562                 let mut witness_lens = BTreeSet::new();
2563                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2564                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2565                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2566                 assert_eq!(witness_lens.len(), 3);
2567                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2568                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2569                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2570
2571                 // Next nodes[1] broadcasts its current local tx state:
2572                 assert_eq!(node_txn[1].input.len(), 1);
2573                 check_spends!(node_txn[1], chan_1.3);
2574
2575                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2576                 // ANTI_REORG_DELAY confirmations.
2577                 mine_transaction(&nodes[1], &node_txn[0]);
2578                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2579                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2580         }
2581         get_announce_close_broadcast_events(&nodes, 0, 1);
2582         assert_eq!(nodes[0].node.list_channels().len(), 0);
2583         assert_eq!(nodes[1].node.list_channels().len(), 0);
2584 }
2585
2586 #[test]
2587 fn claim_htlc_outputs_single_tx() {
2588         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2589         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2590         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2591         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2592         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2593         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2594
2595         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2596
2597         // Rebalance the network to generate htlc in the two directions
2598         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2599         // 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
2600         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2601         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2602         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2603
2604         // Get the will-be-revoked local txn from node[0]
2605         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2606
2607         //Revoke the old state
2608         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2609
2610         {
2611                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2612                 check_added_monitors!(nodes[0], 1);
2613                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2614                 check_added_monitors!(nodes[1], 1);
2615                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2616                 let mut events = nodes[0].node.get_and_clear_pending_events();
2617                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2618                 match events[1] {
2619                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2620                         _ => panic!("Unexpected event"),
2621                 }
2622
2623                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2624                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2625
2626                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2627                 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2628
2629                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2630                 assert_eq!(node_txn[0].input.len(), 1);
2631                 check_spends!(node_txn[0], chan_1.3);
2632                 assert_eq!(node_txn[1].input.len(), 1);
2633                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2634                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2635                 check_spends!(node_txn[1], node_txn[0]);
2636
2637                 // Justice transactions are indices 1-2-4
2638                 assert_eq!(node_txn[2].input.len(), 1);
2639                 assert_eq!(node_txn[3].input.len(), 1);
2640                 assert_eq!(node_txn[4].input.len(), 1);
2641
2642                 check_spends!(node_txn[2], revoked_local_txn[0]);
2643                 check_spends!(node_txn[3], revoked_local_txn[0]);
2644                 check_spends!(node_txn[4], revoked_local_txn[0]);
2645
2646                 let mut witness_lens = BTreeSet::new();
2647                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2648                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2649                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2650                 assert_eq!(witness_lens.len(), 3);
2651                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2652                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2653                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2654
2655                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2656                 // ANTI_REORG_DELAY confirmations.
2657                 mine_transaction(&nodes[1], &node_txn[2]);
2658                 mine_transaction(&nodes[1], &node_txn[3]);
2659                 mine_transaction(&nodes[1], &node_txn[4]);
2660                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2661                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2662         }
2663         get_announce_close_broadcast_events(&nodes, 0, 1);
2664         assert_eq!(nodes[0].node.list_channels().len(), 0);
2665         assert_eq!(nodes[1].node.list_channels().len(), 0);
2666 }
2667
2668 #[test]
2669 fn test_htlc_on_chain_success() {
2670         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2671         // the preimage backward accordingly. So here we test that ChannelManager is
2672         // broadcasting the right event to other nodes in payment path.
2673         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2674         // A --------------------> B ----------------------> C (preimage)
2675         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2676         // commitment transaction was broadcast.
2677         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2678         // towards B.
2679         // B should be able to claim via preimage if A then broadcasts its local tx.
2680         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2681         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2682         // PaymentSent event).
2683
2684         let chanmon_cfgs = create_chanmon_cfgs(3);
2685         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2686         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2687         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2688
2689         // Create some initial channels
2690         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2691         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2692
2693         // Ensure all nodes are at the same height
2694         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2695         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2696         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2697         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2698
2699         // Rebalance the network a bit by relaying one payment through all the channels...
2700         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2701         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2702
2703         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2704         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2705
2706         // Broadcast legit commitment tx from C on B's chain
2707         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2708         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2709         assert_eq!(commitment_tx.len(), 1);
2710         check_spends!(commitment_tx[0], chan_2.3);
2711         nodes[2].node.claim_funds(our_payment_preimage);
2712         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2713         nodes[2].node.claim_funds(our_payment_preimage_2);
2714         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2715         check_added_monitors!(nodes[2], 2);
2716         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2717         assert!(updates.update_add_htlcs.is_empty());
2718         assert!(updates.update_fail_htlcs.is_empty());
2719         assert!(updates.update_fail_malformed_htlcs.is_empty());
2720         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2721
2722         mine_transaction(&nodes[2], &commitment_tx[0]);
2723         check_closed_broadcast!(nodes[2], true);
2724         check_added_monitors!(nodes[2], 1);
2725         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2726         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)
2727         assert_eq!(node_txn.len(), 5);
2728         assert_eq!(node_txn[0], node_txn[3]);
2729         assert_eq!(node_txn[1], node_txn[4]);
2730         assert_eq!(node_txn[2], commitment_tx[0]);
2731         check_spends!(node_txn[0], commitment_tx[0]);
2732         check_spends!(node_txn[1], commitment_tx[0]);
2733         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2734         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2735         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2736         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2737         assert_eq!(node_txn[0].lock_time, 0);
2738         assert_eq!(node_txn[1].lock_time, 0);
2739
2740         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2741         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2742         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2743         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2744         {
2745                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2746                 assert_eq!(added_monitors.len(), 1);
2747                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2748                 added_monitors.clear();
2749         }
2750         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2751         assert_eq!(forwarded_events.len(), 3);
2752         match forwarded_events[0] {
2753                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2754                 _ => panic!("Unexpected event"),
2755         }
2756         let chan_id = Some(chan_1.2);
2757         match forwarded_events[1] {
2758                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2759                         assert_eq!(fee_earned_msat, Some(1000));
2760                         assert_eq!(prev_channel_id, chan_id);
2761                         assert_eq!(claim_from_onchain_tx, true);
2762                         assert_eq!(next_channel_id, Some(chan_2.2));
2763                 },
2764                 _ => panic!()
2765         }
2766         match forwarded_events[2] {
2767                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2768                         assert_eq!(fee_earned_msat, Some(1000));
2769                         assert_eq!(prev_channel_id, chan_id);
2770                         assert_eq!(claim_from_onchain_tx, true);
2771                         assert_eq!(next_channel_id, Some(chan_2.2));
2772                 },
2773                 _ => panic!()
2774         }
2775         let events = nodes[1].node.get_and_clear_pending_msg_events();
2776         {
2777                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2778                 assert_eq!(added_monitors.len(), 2);
2779                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2780                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2781                 added_monitors.clear();
2782         }
2783         assert_eq!(events.len(), 3);
2784         match events[0] {
2785                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2786                 _ => panic!("Unexpected event"),
2787         }
2788         match events[1] {
2789                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2790                 _ => panic!("Unexpected event"),
2791         }
2792
2793         match events[2] {
2794                 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, .. } } => {
2795                         assert!(update_add_htlcs.is_empty());
2796                         assert!(update_fail_htlcs.is_empty());
2797                         assert_eq!(update_fulfill_htlcs.len(), 1);
2798                         assert!(update_fail_malformed_htlcs.is_empty());
2799                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2800                 },
2801                 _ => panic!("Unexpected event"),
2802         };
2803         macro_rules! check_tx_local_broadcast {
2804                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2805                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2806                         assert_eq!(node_txn.len(), 3);
2807                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2808                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2809                         check_spends!(node_txn[1], $commitment_tx);
2810                         check_spends!(node_txn[2], $commitment_tx);
2811                         assert_ne!(node_txn[1].lock_time, 0);
2812                         assert_ne!(node_txn[2].lock_time, 0);
2813                         if $htlc_offered {
2814                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2815                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2816                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2817                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2818                         } else {
2819                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2820                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2821                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2822                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2823                         }
2824                         check_spends!(node_txn[0], $chan_tx);
2825                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2826                         node_txn.clear();
2827                 } }
2828         }
2829         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2830         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2831         // timeout-claim of the output that nodes[2] just claimed via success.
2832         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2833
2834         // Broadcast legit commitment tx from A on B's chain
2835         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2836         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2837         check_spends!(node_a_commitment_tx[0], chan_1.3);
2838         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2839         check_closed_broadcast!(nodes[1], true);
2840         check_added_monitors!(nodes[1], 1);
2841         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2842         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2843         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2844         let commitment_spend =
2845                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2846                         check_spends!(node_txn[1], commitment_tx[0]);
2847                         check_spends!(node_txn[2], commitment_tx[0]);
2848                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2849                         &node_txn[0]
2850                 } else {
2851                         check_spends!(node_txn[0], commitment_tx[0]);
2852                         check_spends!(node_txn[1], commitment_tx[0]);
2853                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2854                         &node_txn[2]
2855                 };
2856
2857         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2858         assert_eq!(commitment_spend.input.len(), 2);
2859         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2860         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2861         assert_eq!(commitment_spend.lock_time, 0);
2862         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2863         check_spends!(node_txn[3], chan_1.3);
2864         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2865         check_spends!(node_txn[4], node_txn[3]);
2866         check_spends!(node_txn[5], node_txn[3]);
2867         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2868         // we already checked the same situation with A.
2869
2870         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2871         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2872         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2873         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2874         check_closed_broadcast!(nodes[0], true);
2875         check_added_monitors!(nodes[0], 1);
2876         let events = nodes[0].node.get_and_clear_pending_events();
2877         assert_eq!(events.len(), 5);
2878         let mut first_claimed = false;
2879         for event in events {
2880                 match event {
2881                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2882                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2883                                         assert!(!first_claimed);
2884                                         first_claimed = true;
2885                                 } else {
2886                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2887                                         assert_eq!(payment_hash, payment_hash_2);
2888                                 }
2889                         },
2890                         Event::PaymentPathSuccessful { .. } => {},
2891                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2892                         _ => panic!("Unexpected event"),
2893                 }
2894         }
2895         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2896 }
2897
2898 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2899         // Test that in case of a unilateral close onchain, we detect the state of output and
2900         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2901         // broadcasting the right event to other nodes in payment path.
2902         // A ------------------> B ----------------------> C (timeout)
2903         //    B's commitment tx                 C's commitment tx
2904         //            \                                  \
2905         //         B's HTLC timeout tx               B's timeout tx
2906
2907         let chanmon_cfgs = create_chanmon_cfgs(3);
2908         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2909         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2910         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2911         *nodes[0].connect_style.borrow_mut() = connect_style;
2912         *nodes[1].connect_style.borrow_mut() = connect_style;
2913         *nodes[2].connect_style.borrow_mut() = connect_style;
2914
2915         // Create some intial channels
2916         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2917         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2918
2919         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2920         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2921         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2922
2923         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2924
2925         // Broadcast legit commitment tx from C on B's chain
2926         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2927         check_spends!(commitment_tx[0], chan_2.3);
2928         nodes[2].node.fail_htlc_backwards(&payment_hash);
2929         check_added_monitors!(nodes[2], 0);
2930         expect_pending_htlcs_forwardable!(nodes[2]);
2931         check_added_monitors!(nodes[2], 1);
2932
2933         let events = nodes[2].node.get_and_clear_pending_msg_events();
2934         assert_eq!(events.len(), 1);
2935         match events[0] {
2936                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2937                         assert!(update_add_htlcs.is_empty());
2938                         assert!(!update_fail_htlcs.is_empty());
2939                         assert!(update_fulfill_htlcs.is_empty());
2940                         assert!(update_fail_malformed_htlcs.is_empty());
2941                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2942                 },
2943                 _ => panic!("Unexpected event"),
2944         };
2945         mine_transaction(&nodes[2], &commitment_tx[0]);
2946         check_closed_broadcast!(nodes[2], true);
2947         check_added_monitors!(nodes[2], 1);
2948         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2949         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2950         assert_eq!(node_txn.len(), 1);
2951         check_spends!(node_txn[0], chan_2.3);
2952         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2953
2954         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2955         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2956         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2957         mine_transaction(&nodes[1], &commitment_tx[0]);
2958         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2959         let timeout_tx;
2960         {
2961                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2962                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2963                 assert_eq!(node_txn[0], node_txn[3]);
2964                 assert_eq!(node_txn[1], node_txn[4]);
2965
2966                 check_spends!(node_txn[2], commitment_tx[0]);
2967                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2968
2969                 check_spends!(node_txn[0], chan_2.3);
2970                 check_spends!(node_txn[1], node_txn[0]);
2971                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2972                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2973
2974                 timeout_tx = node_txn[2].clone();
2975                 node_txn.clear();
2976         }
2977
2978         mine_transaction(&nodes[1], &timeout_tx);
2979         check_added_monitors!(nodes[1], 1);
2980         check_closed_broadcast!(nodes[1], true);
2981         {
2982                 // B will rebroadcast a fee-bumped timeout transaction here.
2983                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2984                 assert_eq!(node_txn.len(), 1);
2985                 check_spends!(node_txn[0], commitment_tx[0]);
2986         }
2987
2988         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2989         {
2990                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2991                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2992                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2993                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2994                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2995                 if node_txn.len() == 1 {
2996                         check_spends!(node_txn[0], chan_2.3);
2997                 } else {
2998                         assert_eq!(node_txn.len(), 0);
2999                 }
3000         }
3001
3002         expect_pending_htlcs_forwardable!(nodes[1]);
3003         check_added_monitors!(nodes[1], 1);
3004         let events = nodes[1].node.get_and_clear_pending_msg_events();
3005         assert_eq!(events.len(), 1);
3006         match events[0] {
3007                 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, .. } } => {
3008                         assert!(update_add_htlcs.is_empty());
3009                         assert!(!update_fail_htlcs.is_empty());
3010                         assert!(update_fulfill_htlcs.is_empty());
3011                         assert!(update_fail_malformed_htlcs.is_empty());
3012                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3013                 },
3014                 _ => panic!("Unexpected event"),
3015         };
3016
3017         // Broadcast legit commitment tx from B on A's chain
3018         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3019         check_spends!(commitment_tx[0], chan_1.3);
3020
3021         mine_transaction(&nodes[0], &commitment_tx[0]);
3022         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3023
3024         check_closed_broadcast!(nodes[0], true);
3025         check_added_monitors!(nodes[0], 1);
3026         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3027         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3028         assert_eq!(node_txn.len(), 2);
3029         check_spends!(node_txn[0], chan_1.3);
3030         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3031         check_spends!(node_txn[1], commitment_tx[0]);
3032         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3033 }
3034
3035 #[test]
3036 fn test_htlc_on_chain_timeout() {
3037         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3038         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3039         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3040 }
3041
3042 #[test]
3043 fn test_simple_commitment_revoked_fail_backward() {
3044         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3045         // and fail backward accordingly.
3046
3047         let chanmon_cfgs = create_chanmon_cfgs(3);
3048         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3049         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3050         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3051
3052         // Create some initial channels
3053         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3054         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3055
3056         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3057         // Get the will-be-revoked local txn from nodes[2]
3058         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3059         // Revoke the old state
3060         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3061
3062         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3063
3064         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3065         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3066         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3067         check_added_monitors!(nodes[1], 1);
3068         check_closed_broadcast!(nodes[1], true);
3069
3070         expect_pending_htlcs_forwardable!(nodes[1]);
3071         check_added_monitors!(nodes[1], 1);
3072         let events = nodes[1].node.get_and_clear_pending_msg_events();
3073         assert_eq!(events.len(), 1);
3074         match events[0] {
3075                 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, .. } } => {
3076                         assert!(update_add_htlcs.is_empty());
3077                         assert_eq!(update_fail_htlcs.len(), 1);
3078                         assert!(update_fulfill_htlcs.is_empty());
3079                         assert!(update_fail_malformed_htlcs.is_empty());
3080                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3081
3082                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3083                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3084                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3085                 },
3086                 _ => panic!("Unexpected event"),
3087         }
3088 }
3089
3090 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3091         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3092         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3093         // commitment transaction anymore.
3094         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3095         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3096         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3097         // technically disallowed and we should probably handle it reasonably.
3098         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3099         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3100         // transactions:
3101         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3102         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3103         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3104         //   and once they revoke the previous commitment transaction (allowing us to send a new
3105         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3106         let chanmon_cfgs = create_chanmon_cfgs(3);
3107         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3108         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3109         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3110
3111         // Create some initial channels
3112         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3113         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3114
3115         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 });
3116         // Get the will-be-revoked local txn from nodes[2]
3117         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3118         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3119         // Revoke the old state
3120         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3121
3122         let value = if use_dust {
3123                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3124                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3125                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3126         } else { 3000000 };
3127
3128         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3129         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3130         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3131
3132         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3133         expect_pending_htlcs_forwardable!(nodes[2]);
3134         check_added_monitors!(nodes[2], 1);
3135         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3136         assert!(updates.update_add_htlcs.is_empty());
3137         assert!(updates.update_fulfill_htlcs.is_empty());
3138         assert!(updates.update_fail_malformed_htlcs.is_empty());
3139         assert_eq!(updates.update_fail_htlcs.len(), 1);
3140         assert!(updates.update_fee.is_none());
3141         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3142         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3143         // Drop the last RAA from 3 -> 2
3144
3145         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3146         expect_pending_htlcs_forwardable!(nodes[2]);
3147         check_added_monitors!(nodes[2], 1);
3148         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3149         assert!(updates.update_add_htlcs.is_empty());
3150         assert!(updates.update_fulfill_htlcs.is_empty());
3151         assert!(updates.update_fail_malformed_htlcs.is_empty());
3152         assert_eq!(updates.update_fail_htlcs.len(), 1);
3153         assert!(updates.update_fee.is_none());
3154         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3155         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3156         check_added_monitors!(nodes[1], 1);
3157         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3158         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3159         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3160         check_added_monitors!(nodes[2], 1);
3161
3162         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3163         expect_pending_htlcs_forwardable!(nodes[2]);
3164         check_added_monitors!(nodes[2], 1);
3165         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3166         assert!(updates.update_add_htlcs.is_empty());
3167         assert!(updates.update_fulfill_htlcs.is_empty());
3168         assert!(updates.update_fail_malformed_htlcs.is_empty());
3169         assert_eq!(updates.update_fail_htlcs.len(), 1);
3170         assert!(updates.update_fee.is_none());
3171         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3172         // At this point first_payment_hash has dropped out of the latest two commitment
3173         // transactions that nodes[1] is tracking...
3174         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3175         check_added_monitors!(nodes[1], 1);
3176         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3177         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3178         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3179         check_added_monitors!(nodes[2], 1);
3180
3181         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3182         // on nodes[2]'s RAA.
3183         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3184         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3185         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3186         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3187         check_added_monitors!(nodes[1], 0);
3188
3189         if deliver_bs_raa {
3190                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3191                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3192                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3193                 check_added_monitors!(nodes[1], 1);
3194                 let events = nodes[1].node.get_and_clear_pending_events();
3195                 assert_eq!(events.len(), 1);
3196                 match events[0] {
3197                         Event::PendingHTLCsForwardable { .. } => { },
3198                         _ => panic!("Unexpected event"),
3199                 };
3200                 // Deliberately don't process the pending fail-back so they all fail back at once after
3201                 // block connection just like the !deliver_bs_raa case
3202         }
3203
3204         let mut failed_htlcs = HashSet::new();
3205         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3206
3207         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3208         check_added_monitors!(nodes[1], 1);
3209         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3210         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3211
3212         let events = nodes[1].node.get_and_clear_pending_events();
3213         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3214         match events[0] {
3215                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3216                 _ => panic!("Unexepected event"),
3217         }
3218         match events[1] {
3219                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3220                         assert_eq!(*payment_hash, fourth_payment_hash);
3221                 },
3222                 _ => panic!("Unexpected event"),
3223         }
3224         if !deliver_bs_raa {
3225                 match events[2] {
3226                         Event::PaymentFailed { ref payment_hash, .. } => {
3227                                 assert_eq!(*payment_hash, fourth_payment_hash);
3228                         },
3229                         _ => panic!("Unexpected event"),
3230                 }
3231                 match events[3] {
3232                         Event::PendingHTLCsForwardable { .. } => { },
3233                         _ => panic!("Unexpected event"),
3234                 };
3235         }
3236         nodes[1].node.process_pending_htlc_forwards();
3237         check_added_monitors!(nodes[1], 1);
3238
3239         let events = nodes[1].node.get_and_clear_pending_msg_events();
3240         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3241         match events[if deliver_bs_raa { 1 } else { 0 }] {
3242                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3243                 _ => panic!("Unexpected event"),
3244         }
3245         match events[if deliver_bs_raa { 2 } else { 1 }] {
3246                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3247                         assert_eq!(channel_id, chan_2.2);
3248                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3249                 },
3250                 _ => panic!("Unexpected event"),
3251         }
3252         if deliver_bs_raa {
3253                 match events[0] {
3254                         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, .. } } => {
3255                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3256                                 assert_eq!(update_add_htlcs.len(), 1);
3257                                 assert!(update_fulfill_htlcs.is_empty());
3258                                 assert!(update_fail_htlcs.is_empty());
3259                                 assert!(update_fail_malformed_htlcs.is_empty());
3260                         },
3261                         _ => panic!("Unexpected event"),
3262                 }
3263         }
3264         match events[if deliver_bs_raa { 3 } else { 2 }] {
3265                 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, .. } } => {
3266                         assert!(update_add_htlcs.is_empty());
3267                         assert_eq!(update_fail_htlcs.len(), 3);
3268                         assert!(update_fulfill_htlcs.is_empty());
3269                         assert!(update_fail_malformed_htlcs.is_empty());
3270                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3271
3272                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3273                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3274                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3275
3276                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3277
3278                         let events = nodes[0].node.get_and_clear_pending_events();
3279                         assert_eq!(events.len(), 3);
3280                         match events[0] {
3281                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3282                                         assert!(failed_htlcs.insert(payment_hash.0));
3283                                         // If we delivered B's RAA we got an unknown preimage error, not something
3284                                         // that we should update our routing table for.
3285                                         if !deliver_bs_raa {
3286                                                 assert!(network_update.is_some());
3287                                         }
3288                                 },
3289                                 _ => panic!("Unexpected event"),
3290                         }
3291                         match events[1] {
3292                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3293                                         assert!(failed_htlcs.insert(payment_hash.0));
3294                                         assert!(network_update.is_some());
3295                                 },
3296                                 _ => panic!("Unexpected event"),
3297                         }
3298                         match events[2] {
3299                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3300                                         assert!(failed_htlcs.insert(payment_hash.0));
3301                                         assert!(network_update.is_some());
3302                                 },
3303                                 _ => panic!("Unexpected event"),
3304                         }
3305                 },
3306                 _ => panic!("Unexpected event"),
3307         }
3308
3309         assert!(failed_htlcs.contains(&first_payment_hash.0));
3310         assert!(failed_htlcs.contains(&second_payment_hash.0));
3311         assert!(failed_htlcs.contains(&third_payment_hash.0));
3312 }
3313
3314 #[test]
3315 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3316         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3317         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3318         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3319         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3320 }
3321
3322 #[test]
3323 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3324         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3325         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3326         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3327         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3328 }
3329
3330 #[test]
3331 fn fail_backward_pending_htlc_upon_channel_failure() {
3332         let chanmon_cfgs = create_chanmon_cfgs(2);
3333         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3334         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3335         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3336         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3337
3338         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3339         {
3340                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3341                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3342                 check_added_monitors!(nodes[0], 1);
3343
3344                 let payment_event = {
3345                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3346                         assert_eq!(events.len(), 1);
3347                         SendEvent::from_event(events.remove(0))
3348                 };
3349                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3350                 assert_eq!(payment_event.msgs.len(), 1);
3351         }
3352
3353         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3354         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3355         {
3356                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3357                 check_added_monitors!(nodes[0], 0);
3358
3359                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3360         }
3361
3362         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3363         {
3364                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3365
3366                 let secp_ctx = Secp256k1::new();
3367                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3368                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3369                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3370                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3371                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3372
3373                 // Send a 0-msat update_add_htlc to fail the channel.
3374                 let update_add_htlc = msgs::UpdateAddHTLC {
3375                         channel_id: chan.2,
3376                         htlc_id: 0,
3377                         amount_msat: 0,
3378                         payment_hash,
3379                         cltv_expiry,
3380                         onion_routing_packet,
3381                 };
3382                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3383         }
3384         let events = nodes[0].node.get_and_clear_pending_events();
3385         assert_eq!(events.len(), 2);
3386         // Check that Alice fails backward the pending HTLC from the second payment.
3387         match events[0] {
3388                 Event::PaymentPathFailed { payment_hash, .. } => {
3389                         assert_eq!(payment_hash, failed_payment_hash);
3390                 },
3391                 _ => panic!("Unexpected event"),
3392         }
3393         match events[1] {
3394                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3395                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3396                 },
3397                 _ => panic!("Unexpected event {:?}", events[1]),
3398         }
3399         check_closed_broadcast!(nodes[0], true);
3400         check_added_monitors!(nodes[0], 1);
3401 }
3402
3403 #[test]
3404 fn test_htlc_ignore_latest_remote_commitment() {
3405         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3406         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3407         let chanmon_cfgs = create_chanmon_cfgs(2);
3408         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3409         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3410         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3411         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3412
3413         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3414         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3415         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3416         check_closed_broadcast!(nodes[0], true);
3417         check_added_monitors!(nodes[0], 1);
3418         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3419
3420         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3421         assert_eq!(node_txn.len(), 3);
3422         assert_eq!(node_txn[0], node_txn[1]);
3423
3424         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3425         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3426         check_closed_broadcast!(nodes[1], true);
3427         check_added_monitors!(nodes[1], 1);
3428         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3429
3430         // Duplicate the connect_block call since this may happen due to other listeners
3431         // registering new transactions
3432         header.prev_blockhash = header.block_hash();
3433         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3434 }
3435
3436 #[test]
3437 fn test_force_close_fail_back() {
3438         // Check which HTLCs are failed-backwards on channel force-closure
3439         let chanmon_cfgs = create_chanmon_cfgs(3);
3440         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3441         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3442         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3443         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3444         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3445
3446         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3447
3448         let mut payment_event = {
3449                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3450                 check_added_monitors!(nodes[0], 1);
3451
3452                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3453                 assert_eq!(events.len(), 1);
3454                 SendEvent::from_event(events.remove(0))
3455         };
3456
3457         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3458         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3459
3460         expect_pending_htlcs_forwardable!(nodes[1]);
3461
3462         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3463         assert_eq!(events_2.len(), 1);
3464         payment_event = SendEvent::from_event(events_2.remove(0));
3465         assert_eq!(payment_event.msgs.len(), 1);
3466
3467         check_added_monitors!(nodes[1], 1);
3468         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3469         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3470         check_added_monitors!(nodes[2], 1);
3471         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3472
3473         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3474         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3475         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3476
3477         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3478         check_closed_broadcast!(nodes[2], true);
3479         check_added_monitors!(nodes[2], 1);
3480         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3481         let tx = {
3482                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3483                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3484                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3485                 // back to nodes[1] upon timeout otherwise.
3486                 assert_eq!(node_txn.len(), 1);
3487                 node_txn.remove(0)
3488         };
3489
3490         mine_transaction(&nodes[1], &tx);
3491
3492         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3493         check_closed_broadcast!(nodes[1], true);
3494         check_added_monitors!(nodes[1], 1);
3495         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3496
3497         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3498         {
3499                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3500                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3501         }
3502         mine_transaction(&nodes[2], &tx);
3503         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3504         assert_eq!(node_txn.len(), 1);
3505         assert_eq!(node_txn[0].input.len(), 1);
3506         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3507         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3508         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3509
3510         check_spends!(node_txn[0], tx);
3511 }
3512
3513 #[test]
3514 fn test_dup_events_on_peer_disconnect() {
3515         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3516         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3517         // as we used to generate the event immediately upon receipt of the payment preimage in the
3518         // update_fulfill_htlc message.
3519
3520         let chanmon_cfgs = create_chanmon_cfgs(2);
3521         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3522         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3523         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3524         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3525
3526         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3527
3528         nodes[1].node.claim_funds(payment_preimage);
3529         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3530         check_added_monitors!(nodes[1], 1);
3531         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3532         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3533         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3534
3535         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3536         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3537
3538         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3539         expect_payment_path_successful!(nodes[0]);
3540 }
3541
3542 #[test]
3543 fn test_peer_disconnected_before_funding_broadcasted() {
3544         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3545         // before the funding transaction has been broadcasted.
3546         let chanmon_cfgs = create_chanmon_cfgs(2);
3547         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3548         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3549         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3550
3551         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3552         // broadcasted, even though it's created by `nodes[0]`.
3553         let expected_temporary_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
3554         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3555         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3556         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3557         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3558
3559         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3560         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3561
3562         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3563
3564         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3565         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3566
3567         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3568         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3569         // broadcasted.
3570         {
3571                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3572         }
3573
3574         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3575         // disconnected before the funding transaction was broadcasted.
3576         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3577         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3578
3579         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3580         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3581 }
3582
3583 #[test]
3584 fn test_simple_peer_disconnect() {
3585         // Test that we can reconnect when there are no lost messages
3586         let chanmon_cfgs = create_chanmon_cfgs(3);
3587         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3588         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3589         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3590         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3591         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3592
3593         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3594         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3595         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3596
3597         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3598         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3599         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3600         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3601
3602         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3603         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3604         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3605
3606         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3607         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3608         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3609         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3610
3611         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3612         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3613
3614         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3615         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3616
3617         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3618         {
3619                 let events = nodes[0].node.get_and_clear_pending_events();
3620                 assert_eq!(events.len(), 3);
3621                 match events[0] {
3622                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3623                                 assert_eq!(payment_preimage, payment_preimage_3);
3624                                 assert_eq!(payment_hash, payment_hash_3);
3625                         },
3626                         _ => panic!("Unexpected event"),
3627                 }
3628                 match events[1] {
3629                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3630                                 assert_eq!(payment_hash, payment_hash_5);
3631                                 assert!(rejected_by_dest);
3632                         },
3633                         _ => panic!("Unexpected event"),
3634                 }
3635                 match events[2] {
3636                         Event::PaymentPathSuccessful { .. } => {},
3637                         _ => panic!("Unexpected event"),
3638                 }
3639         }
3640
3641         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3642         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3643 }
3644
3645 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3646         // Test that we can reconnect when in-flight HTLC updates get dropped
3647         let chanmon_cfgs = create_chanmon_cfgs(2);
3648         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3649         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3650         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3651
3652         let mut as_channel_ready = None;
3653         if messages_delivered == 0 {
3654                 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3655                 as_channel_ready = Some(channel_ready);
3656                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3657                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3658                 // it before the channel_reestablish message.
3659         } else {
3660                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3661         }
3662
3663         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3664
3665         let payment_event = {
3666                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3667                 check_added_monitors!(nodes[0], 1);
3668
3669                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3670                 assert_eq!(events.len(), 1);
3671                 SendEvent::from_event(events.remove(0))
3672         };
3673         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3674
3675         if messages_delivered < 2 {
3676                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3677         } else {
3678                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3679                 if messages_delivered >= 3 {
3680                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3681                         check_added_monitors!(nodes[1], 1);
3682                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3683
3684                         if messages_delivered >= 4 {
3685                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3686                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3687                                 check_added_monitors!(nodes[0], 1);
3688
3689                                 if messages_delivered >= 5 {
3690                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3691                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3692                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3693                                         check_added_monitors!(nodes[0], 1);
3694
3695                                         if messages_delivered >= 6 {
3696                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3697                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3698                                                 check_added_monitors!(nodes[1], 1);
3699                                         }
3700                                 }
3701                         }
3702                 }
3703         }
3704
3705         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3706         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3707         if messages_delivered < 3 {
3708                 if simulate_broken_lnd {
3709                         // lnd has a long-standing bug where they send a channel_ready prior to a
3710                         // channel_reestablish if you reconnect prior to channel_ready time.
3711                         //
3712                         // Here we simulate that behavior, delivering a channel_ready immediately on
3713                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3714                         // in `reconnect_nodes` but we currently don't fail based on that.
3715                         //
3716                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3717                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3718                 }
3719                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3720                 // received on either side, both sides will need to resend them.
3721                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3722         } else if messages_delivered == 3 {
3723                 // nodes[0] still wants its RAA + commitment_signed
3724                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3725         } else if messages_delivered == 4 {
3726                 // nodes[0] still wants its commitment_signed
3727                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3728         } else if messages_delivered == 5 {
3729                 // nodes[1] still wants its final RAA
3730                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3731         } else if messages_delivered == 6 {
3732                 // Everything was delivered...
3733                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3734         }
3735
3736         let events_1 = nodes[1].node.get_and_clear_pending_events();
3737         assert_eq!(events_1.len(), 1);
3738         match events_1[0] {
3739                 Event::PendingHTLCsForwardable { .. } => { },
3740                 _ => panic!("Unexpected event"),
3741         };
3742
3743         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3744         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3745         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3746
3747         nodes[1].node.process_pending_htlc_forwards();
3748
3749         let events_2 = nodes[1].node.get_and_clear_pending_events();
3750         assert_eq!(events_2.len(), 1);
3751         match events_2[0] {
3752                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3753                         assert_eq!(payment_hash_1, *payment_hash);
3754                         assert_eq!(amount_msat, 1_000_000);
3755                         match &purpose {
3756                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3757                                         assert!(payment_preimage.is_none());
3758                                         assert_eq!(payment_secret_1, *payment_secret);
3759                                 },
3760                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3761                         }
3762                 },
3763                 _ => panic!("Unexpected event"),
3764         }
3765
3766         nodes[1].node.claim_funds(payment_preimage_1);
3767         check_added_monitors!(nodes[1], 1);
3768         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3769
3770         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3771         assert_eq!(events_3.len(), 1);
3772         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3773                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3774                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3775                         assert!(updates.update_add_htlcs.is_empty());
3776                         assert!(updates.update_fail_htlcs.is_empty());
3777                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3778                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3779                         assert!(updates.update_fee.is_none());
3780                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3781                 },
3782                 _ => panic!("Unexpected event"),
3783         };
3784
3785         if messages_delivered >= 1 {
3786                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3787
3788                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3789                 assert_eq!(events_4.len(), 1);
3790                 match events_4[0] {
3791                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3792                                 assert_eq!(payment_preimage_1, *payment_preimage);
3793                                 assert_eq!(payment_hash_1, *payment_hash);
3794                         },
3795                         _ => panic!("Unexpected event"),
3796                 }
3797
3798                 if messages_delivered >= 2 {
3799                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3800                         check_added_monitors!(nodes[0], 1);
3801                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3802
3803                         if messages_delivered >= 3 {
3804                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3805                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3806                                 check_added_monitors!(nodes[1], 1);
3807
3808                                 if messages_delivered >= 4 {
3809                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3810                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3811                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3812                                         check_added_monitors!(nodes[1], 1);
3813
3814                                         if messages_delivered >= 5 {
3815                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3816                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3817                                                 check_added_monitors!(nodes[0], 1);
3818                                         }
3819                                 }
3820                         }
3821                 }
3822         }
3823
3824         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3825         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3826         if messages_delivered < 2 {
3827                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3828                 if messages_delivered < 1 {
3829                         expect_payment_sent!(nodes[0], payment_preimage_1);
3830                 } else {
3831                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3832                 }
3833         } else if messages_delivered == 2 {
3834                 // nodes[0] still wants its RAA + commitment_signed
3835                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3836         } else if messages_delivered == 3 {
3837                 // nodes[0] still wants its commitment_signed
3838                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3839         } else if messages_delivered == 4 {
3840                 // nodes[1] still wants its final RAA
3841                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3842         } else if messages_delivered == 5 {
3843                 // Everything was delivered...
3844                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3845         }
3846
3847         if messages_delivered == 1 || messages_delivered == 2 {
3848                 expect_payment_path_successful!(nodes[0]);
3849         }
3850
3851         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3852         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3853         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3854
3855         if messages_delivered > 2 {
3856                 expect_payment_path_successful!(nodes[0]);
3857         }
3858
3859         // Channel should still work fine...
3860         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3861         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3862         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3863 }
3864
3865 #[test]
3866 fn test_drop_messages_peer_disconnect_a() {
3867         do_test_drop_messages_peer_disconnect(0, true);
3868         do_test_drop_messages_peer_disconnect(0, false);
3869         do_test_drop_messages_peer_disconnect(1, false);
3870         do_test_drop_messages_peer_disconnect(2, false);
3871 }
3872
3873 #[test]
3874 fn test_drop_messages_peer_disconnect_b() {
3875         do_test_drop_messages_peer_disconnect(3, false);
3876         do_test_drop_messages_peer_disconnect(4, false);
3877         do_test_drop_messages_peer_disconnect(5, false);
3878         do_test_drop_messages_peer_disconnect(6, false);
3879 }
3880
3881 #[test]
3882 fn test_funding_peer_disconnect() {
3883         // Test that we can lock in our funding tx while disconnected
3884         let chanmon_cfgs = create_chanmon_cfgs(2);
3885         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3886         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3887         let persister: test_utils::TestPersister;
3888         let new_chain_monitor: test_utils::TestChainMonitor;
3889         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3890         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3891         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3892
3893         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3894         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3895
3896         confirm_transaction(&nodes[0], &tx);
3897         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3898         assert!(events_1.is_empty());
3899
3900         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3901
3902         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3903         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3904
3905         confirm_transaction(&nodes[1], &tx);
3906         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3907         assert!(events_2.is_empty());
3908
3909         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3910         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3911         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3912         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3913
3914         // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3915         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3916         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3917         assert_eq!(events_3.len(), 1);
3918         let as_channel_ready = match events_3[0] {
3919                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3920                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3921                         msg.clone()
3922                 },
3923                 _ => panic!("Unexpected event {:?}", events_3[0]),
3924         };
3925
3926         // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3927         // announcement_signatures as well as channel_update.
3928         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3929         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3930         assert_eq!(events_4.len(), 3);
3931         let chan_id;
3932         let bs_channel_ready = match events_4[0] {
3933                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3934                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3935                         chan_id = msg.channel_id;
3936                         msg.clone()
3937                 },
3938                 _ => panic!("Unexpected event {:?}", events_4[0]),
3939         };
3940         let bs_announcement_sigs = match events_4[1] {
3941                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3942                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3943                         msg.clone()
3944                 },
3945                 _ => panic!("Unexpected event {:?}", events_4[1]),
3946         };
3947         match events_4[2] {
3948                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3949                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3950                 },
3951                 _ => panic!("Unexpected event {:?}", events_4[2]),
3952         }
3953
3954         // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3955         // generates a duplicative private channel_update
3956         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3957         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3958         assert_eq!(events_5.len(), 1);
3959         match events_5[0] {
3960                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3961                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3962                 },
3963                 _ => panic!("Unexpected event {:?}", events_5[0]),
3964         };
3965
3966         // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3967         // announcement_signatures.
3968         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3969         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3970         assert_eq!(events_6.len(), 1);
3971         let as_announcement_sigs = match events_6[0] {
3972                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3973                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3974                         msg.clone()
3975                 },
3976                 _ => panic!("Unexpected event {:?}", events_6[0]),
3977         };
3978
3979         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3980         // broadcast the channel announcement globally, as well as re-send its (now-public)
3981         // channel_update.
3982         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3983         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3984         assert_eq!(events_7.len(), 1);
3985         let (chan_announcement, as_update) = match events_7[0] {
3986                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3987                         (msg.clone(), update_msg.clone())
3988                 },
3989                 _ => panic!("Unexpected event {:?}", events_7[0]),
3990         };
3991
3992         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3993         // same channel_announcement.
3994         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3995         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3996         assert_eq!(events_8.len(), 1);
3997         let bs_update = match events_8[0] {
3998                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3999                         assert_eq!(*msg, chan_announcement);
4000                         update_msg.clone()
4001                 },
4002                 _ => panic!("Unexpected event {:?}", events_8[0]),
4003         };
4004
4005         // Provide the channel announcement and public updates to the network graph
4006         nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
4007         nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
4008         nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
4009
4010         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4011         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4012         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
4013
4014         // Check that after deserialization and reconnection we can still generate an identical
4015         // channel_announcement from the cached signatures.
4016         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4017
4018         let nodes_0_serialized = nodes[0].node.encode();
4019         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4020         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4021
4022         persister = test_utils::TestPersister::new();
4023         let keys_manager = &chanmon_cfgs[0].keys_manager;
4024         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);
4025         nodes[0].chain_monitor = &new_chain_monitor;
4026         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4027         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4028                 &mut chan_0_monitor_read, keys_manager).unwrap();
4029         assert!(chan_0_monitor_read.is_empty());
4030
4031         let mut nodes_0_read = &nodes_0_serialized[..];
4032         let (_, nodes_0_deserialized_tmp) = {
4033                 let mut channel_monitors = HashMap::new();
4034                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4035                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4036                         default_config: UserConfig::default(),
4037                         keys_manager,
4038                         fee_estimator: node_cfgs[0].fee_estimator,
4039                         chain_monitor: nodes[0].chain_monitor,
4040                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4041                         logger: nodes[0].logger,
4042                         channel_monitors,
4043                 }).unwrap()
4044         };
4045         nodes_0_deserialized = nodes_0_deserialized_tmp;
4046         assert!(nodes_0_read.is_empty());
4047
4048         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4049         nodes[0].node = &nodes_0_deserialized;
4050         check_added_monitors!(nodes[0], 1);
4051
4052         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4053
4054         // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4055         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4056         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4057         let mut found_announcement = false;
4058         for event in msgs.iter() {
4059                 match event {
4060                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4061                                 if *msg == chan_announcement { found_announcement = true; }
4062                         },
4063                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4064                         _ => panic!("Unexpected event"),
4065                 }
4066         }
4067         assert!(found_announcement);
4068 }
4069
4070 #[test]
4071 fn test_channel_ready_without_best_block_updated() {
4072         // Previously, if we were offline when a funding transaction was locked in, and then we came
4073         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4074         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4075         // channel_ready immediately instead.
4076         let chanmon_cfgs = create_chanmon_cfgs(2);
4077         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4078         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4079         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4080         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4081
4082         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4083
4084         let conf_height = nodes[0].best_block_info().1 + 1;
4085         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4086         let block_txn = [funding_tx];
4087         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4088         let conf_block_header = nodes[0].get_block_header(conf_height);
4089         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4090
4091         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4092         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4093         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4094 }
4095
4096 #[test]
4097 fn test_drop_messages_peer_disconnect_dual_htlc() {
4098         // Test that we can handle reconnecting when both sides of a channel have pending
4099         // commitment_updates when we disconnect.
4100         let chanmon_cfgs = create_chanmon_cfgs(2);
4101         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4102         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4103         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4104         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4105
4106         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4107
4108         // Now try to send a second payment which will fail to send
4109         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4110         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4111         check_added_monitors!(nodes[0], 1);
4112
4113         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4114         assert_eq!(events_1.len(), 1);
4115         match events_1[0] {
4116                 MessageSendEvent::UpdateHTLCs { .. } => {},
4117                 _ => panic!("Unexpected event"),
4118         }
4119
4120         nodes[1].node.claim_funds(payment_preimage_1);
4121         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4122         check_added_monitors!(nodes[1], 1);
4123
4124         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4125         assert_eq!(events_2.len(), 1);
4126         match events_2[0] {
4127                 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 } } => {
4128                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4129                         assert!(update_add_htlcs.is_empty());
4130                         assert_eq!(update_fulfill_htlcs.len(), 1);
4131                         assert!(update_fail_htlcs.is_empty());
4132                         assert!(update_fail_malformed_htlcs.is_empty());
4133                         assert!(update_fee.is_none());
4134
4135                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4136                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4137                         assert_eq!(events_3.len(), 1);
4138                         match events_3[0] {
4139                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4140                                         assert_eq!(*payment_preimage, payment_preimage_1);
4141                                         assert_eq!(*payment_hash, payment_hash_1);
4142                                 },
4143                                 _ => panic!("Unexpected event"),
4144                         }
4145
4146                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4147                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4148                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4149                         check_added_monitors!(nodes[0], 1);
4150                 },
4151                 _ => panic!("Unexpected event"),
4152         }
4153
4154         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4155         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4156
4157         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4158         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4159         assert_eq!(reestablish_1.len(), 1);
4160         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4161         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4162         assert_eq!(reestablish_2.len(), 1);
4163
4164         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4165         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4166         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4167         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4168
4169         assert!(as_resp.0.is_none());
4170         assert!(bs_resp.0.is_none());
4171
4172         assert!(bs_resp.1.is_none());
4173         assert!(bs_resp.2.is_none());
4174
4175         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4176
4177         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4178         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4179         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4180         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4181         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4182         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4183         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4184         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4185         // No commitment_signed so get_event_msg's assert(len == 1) passes
4186         check_added_monitors!(nodes[1], 1);
4187
4188         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4189         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4190         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4191         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4192         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4193         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4194         assert!(bs_second_commitment_signed.update_fee.is_none());
4195         check_added_monitors!(nodes[1], 1);
4196
4197         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4198         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4199         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4200         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4201         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4202         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4203         assert!(as_commitment_signed.update_fee.is_none());
4204         check_added_monitors!(nodes[0], 1);
4205
4206         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4207         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4208         // No commitment_signed so get_event_msg's assert(len == 1) passes
4209         check_added_monitors!(nodes[0], 1);
4210
4211         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4212         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4213         // No commitment_signed so get_event_msg's assert(len == 1) passes
4214         check_added_monitors!(nodes[1], 1);
4215
4216         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4217         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4218         check_added_monitors!(nodes[1], 1);
4219
4220         expect_pending_htlcs_forwardable!(nodes[1]);
4221
4222         let events_5 = nodes[1].node.get_and_clear_pending_events();
4223         assert_eq!(events_5.len(), 1);
4224         match events_5[0] {
4225                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4226                         assert_eq!(payment_hash_2, *payment_hash);
4227                         match &purpose {
4228                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4229                                         assert!(payment_preimage.is_none());
4230                                         assert_eq!(payment_secret_2, *payment_secret);
4231                                 },
4232                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4233                         }
4234                 },
4235                 _ => panic!("Unexpected event"),
4236         }
4237
4238         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4239         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4240         check_added_monitors!(nodes[0], 1);
4241
4242         expect_payment_path_successful!(nodes[0]);
4243         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4244 }
4245
4246 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4247         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4248         // to avoid our counterparty failing the channel.
4249         let chanmon_cfgs = create_chanmon_cfgs(2);
4250         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4251         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4252         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4253
4254         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4255
4256         let our_payment_hash = if send_partial_mpp {
4257                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4258                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4259                 // indicates there are more HTLCs coming.
4260                 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.
4261                 let payment_id = PaymentId([42; 32]);
4262                 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();
4263                 check_added_monitors!(nodes[0], 1);
4264                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4265                 assert_eq!(events.len(), 1);
4266                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4267                 // hop should *not* yet generate any PaymentReceived event(s).
4268                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4269                 our_payment_hash
4270         } else {
4271                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4272         };
4273
4274         let mut block = Block {
4275                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4276                 txdata: vec![],
4277         };
4278         connect_block(&nodes[0], &block);
4279         connect_block(&nodes[1], &block);
4280         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4281         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4282                 block.header.prev_blockhash = block.block_hash();
4283                 connect_block(&nodes[0], &block);
4284                 connect_block(&nodes[1], &block);
4285         }
4286
4287         expect_pending_htlcs_forwardable!(nodes[1]);
4288
4289         check_added_monitors!(nodes[1], 1);
4290         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4291         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4292         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4293         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4294         assert!(htlc_timeout_updates.update_fee.is_none());
4295
4296         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4297         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4298         // 100_000 msat as u64, followed by the height at which we failed back above
4299         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4300         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4301         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4302 }
4303
4304 #[test]
4305 fn test_htlc_timeout() {
4306         do_test_htlc_timeout(true);
4307         do_test_htlc_timeout(false);
4308 }
4309
4310 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4311         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4312         let chanmon_cfgs = create_chanmon_cfgs(3);
4313         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4314         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4315         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4316         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4317         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4318
4319         // Make sure all nodes are at the same starting height
4320         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4321         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4322         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4323
4324         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4325         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4326         {
4327                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4328         }
4329         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4330         check_added_monitors!(nodes[1], 1);
4331
4332         // Now attempt to route a second payment, which should be placed in the holding cell
4333         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4334         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4335         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4336         if forwarded_htlc {
4337                 check_added_monitors!(nodes[0], 1);
4338                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4339                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4340                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4341                 expect_pending_htlcs_forwardable!(nodes[1]);
4342         }
4343         check_added_monitors!(nodes[1], 0);
4344
4345         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4346         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4347         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4348         connect_blocks(&nodes[1], 1);
4349
4350         if forwarded_htlc {
4351                 expect_pending_htlcs_forwardable!(nodes[1]);
4352                 check_added_monitors!(nodes[1], 1);
4353                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4354                 assert_eq!(fail_commit.len(), 1);
4355                 match fail_commit[0] {
4356                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4357                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4358                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4359                         },
4360                         _ => unreachable!(),
4361                 }
4362                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4363         } else {
4364                 let events = nodes[1].node.get_and_clear_pending_events();
4365                 assert_eq!(events.len(), 2);
4366                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4367                         assert_eq!(*payment_hash, second_payment_hash);
4368                 } else { panic!("Unexpected event"); }
4369                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4370                         assert_eq!(*payment_hash, second_payment_hash);
4371                 } else { panic!("Unexpected event"); }
4372         }
4373 }
4374
4375 #[test]
4376 fn test_holding_cell_htlc_add_timeouts() {
4377         do_test_holding_cell_htlc_add_timeouts(false);
4378         do_test_holding_cell_htlc_add_timeouts(true);
4379 }
4380
4381 #[test]
4382 fn test_no_txn_manager_serialize_deserialize() {
4383         let chanmon_cfgs = create_chanmon_cfgs(2);
4384         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4385         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4386         let logger: test_utils::TestLogger;
4387         let fee_estimator: test_utils::TestFeeEstimator;
4388         let persister: test_utils::TestPersister;
4389         let new_chain_monitor: test_utils::TestChainMonitor;
4390         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4391         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4392
4393         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4394
4395         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4396
4397         let nodes_0_serialized = nodes[0].node.encode();
4398         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4399         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4400                 .write(&mut chan_0_monitor_serialized).unwrap();
4401
4402         logger = test_utils::TestLogger::new();
4403         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4404         persister = test_utils::TestPersister::new();
4405         let keys_manager = &chanmon_cfgs[0].keys_manager;
4406         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4407         nodes[0].chain_monitor = &new_chain_monitor;
4408         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4409         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4410                 &mut chan_0_monitor_read, keys_manager).unwrap();
4411         assert!(chan_0_monitor_read.is_empty());
4412
4413         let mut nodes_0_read = &nodes_0_serialized[..];
4414         let config = UserConfig::default();
4415         let (_, nodes_0_deserialized_tmp) = {
4416                 let mut channel_monitors = HashMap::new();
4417                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4418                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4419                         default_config: config,
4420                         keys_manager,
4421                         fee_estimator: &fee_estimator,
4422                         chain_monitor: nodes[0].chain_monitor,
4423                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4424                         logger: &logger,
4425                         channel_monitors,
4426                 }).unwrap()
4427         };
4428         nodes_0_deserialized = nodes_0_deserialized_tmp;
4429         assert!(nodes_0_read.is_empty());
4430
4431         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4432         nodes[0].node = &nodes_0_deserialized;
4433         assert_eq!(nodes[0].node.list_channels().len(), 1);
4434         check_added_monitors!(nodes[0], 1);
4435
4436         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4437         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4438         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4439         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4440
4441         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4442         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4443         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4444         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4445
4446         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4447         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4448         for node in nodes.iter() {
4449                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4450                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4451                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4452         }
4453
4454         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4455 }
4456
4457 #[test]
4458 fn test_manager_serialize_deserialize_events() {
4459         // This test makes sure the events field in ChannelManager survives de/serialization
4460         let chanmon_cfgs = create_chanmon_cfgs(2);
4461         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4462         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4463         let fee_estimator: test_utils::TestFeeEstimator;
4464         let persister: test_utils::TestPersister;
4465         let logger: test_utils::TestLogger;
4466         let new_chain_monitor: test_utils::TestChainMonitor;
4467         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4468         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4469
4470         // Start creating a channel, but stop right before broadcasting the funding transaction
4471         let channel_value = 100000;
4472         let push_msat = 10001;
4473         let a_flags = InitFeatures::known();
4474         let b_flags = InitFeatures::known();
4475         let node_a = nodes.remove(0);
4476         let node_b = nodes.remove(0);
4477         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4478         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()));
4479         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()));
4480
4481         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4482
4483         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4484         check_added_monitors!(node_a, 0);
4485
4486         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()));
4487         {
4488                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4489                 assert_eq!(added_monitors.len(), 1);
4490                 assert_eq!(added_monitors[0].0, funding_output);
4491                 added_monitors.clear();
4492         }
4493
4494         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4495         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4496         {
4497                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4498                 assert_eq!(added_monitors.len(), 1);
4499                 assert_eq!(added_monitors[0].0, funding_output);
4500                 added_monitors.clear();
4501         }
4502         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4503
4504         nodes.push(node_a);
4505         nodes.push(node_b);
4506
4507         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4508         let nodes_0_serialized = nodes[0].node.encode();
4509         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4510         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4511
4512         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4513         logger = test_utils::TestLogger::new();
4514         persister = test_utils::TestPersister::new();
4515         let keys_manager = &chanmon_cfgs[0].keys_manager;
4516         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4517         nodes[0].chain_monitor = &new_chain_monitor;
4518         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4519         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4520                 &mut chan_0_monitor_read, keys_manager).unwrap();
4521         assert!(chan_0_monitor_read.is_empty());
4522
4523         let mut nodes_0_read = &nodes_0_serialized[..];
4524         let config = UserConfig::default();
4525         let (_, nodes_0_deserialized_tmp) = {
4526                 let mut channel_monitors = HashMap::new();
4527                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4528                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4529                         default_config: config,
4530                         keys_manager,
4531                         fee_estimator: &fee_estimator,
4532                         chain_monitor: nodes[0].chain_monitor,
4533                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4534                         logger: &logger,
4535                         channel_monitors,
4536                 }).unwrap()
4537         };
4538         nodes_0_deserialized = nodes_0_deserialized_tmp;
4539         assert!(nodes_0_read.is_empty());
4540
4541         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4542
4543         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4544         nodes[0].node = &nodes_0_deserialized;
4545
4546         // After deserializing, make sure the funding_transaction is still held by the channel manager
4547         let events_4 = nodes[0].node.get_and_clear_pending_events();
4548         assert_eq!(events_4.len(), 0);
4549         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4550         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4551
4552         // Make sure the channel is functioning as though the de/serialization never happened
4553         assert_eq!(nodes[0].node.list_channels().len(), 1);
4554         check_added_monitors!(nodes[0], 1);
4555
4556         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4557         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4558         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4559         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4560
4561         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4562         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4563         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4564         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4565
4566         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4567         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4568         for node in nodes.iter() {
4569                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4570                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4571                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4572         }
4573
4574         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4575 }
4576
4577 #[test]
4578 fn test_simple_manager_serialize_deserialize() {
4579         let chanmon_cfgs = create_chanmon_cfgs(2);
4580         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4581         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4582         let logger: test_utils::TestLogger;
4583         let fee_estimator: test_utils::TestFeeEstimator;
4584         let persister: test_utils::TestPersister;
4585         let new_chain_monitor: test_utils::TestChainMonitor;
4586         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4587         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4588         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4589
4590         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4591         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4592
4593         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4594
4595         let nodes_0_serialized = nodes[0].node.encode();
4596         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4597         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4598
4599         logger = test_utils::TestLogger::new();
4600         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4601         persister = test_utils::TestPersister::new();
4602         let keys_manager = &chanmon_cfgs[0].keys_manager;
4603         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4604         nodes[0].chain_monitor = &new_chain_monitor;
4605         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4606         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4607                 &mut chan_0_monitor_read, keys_manager).unwrap();
4608         assert!(chan_0_monitor_read.is_empty());
4609
4610         let mut nodes_0_read = &nodes_0_serialized[..];
4611         let (_, nodes_0_deserialized_tmp) = {
4612                 let mut channel_monitors = HashMap::new();
4613                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4614                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4615                         default_config: UserConfig::default(),
4616                         keys_manager,
4617                         fee_estimator: &fee_estimator,
4618                         chain_monitor: nodes[0].chain_monitor,
4619                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4620                         logger: &logger,
4621                         channel_monitors,
4622                 }).unwrap()
4623         };
4624         nodes_0_deserialized = nodes_0_deserialized_tmp;
4625         assert!(nodes_0_read.is_empty());
4626
4627         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4628         nodes[0].node = &nodes_0_deserialized;
4629         check_added_monitors!(nodes[0], 1);
4630
4631         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4632
4633         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4634         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4635 }
4636
4637 #[test]
4638 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4639         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4640         let chanmon_cfgs = create_chanmon_cfgs(4);
4641         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4642         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4643         let logger: test_utils::TestLogger;
4644         let fee_estimator: test_utils::TestFeeEstimator;
4645         let persister: test_utils::TestPersister;
4646         let new_chain_monitor: test_utils::TestChainMonitor;
4647         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4648         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4649         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4650         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4651         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4652
4653         let mut node_0_stale_monitors_serialized = Vec::new();
4654         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4655                 let mut writer = test_utils::TestVecWriter(Vec::new());
4656                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4657                 node_0_stale_monitors_serialized.push(writer.0);
4658         }
4659
4660         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4661
4662         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4663         let nodes_0_serialized = nodes[0].node.encode();
4664
4665         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4666         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4667         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4668         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4669
4670         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4671         // nodes[3])
4672         let mut node_0_monitors_serialized = Vec::new();
4673         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4674                 let mut writer = test_utils::TestVecWriter(Vec::new());
4675                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4676                 node_0_monitors_serialized.push(writer.0);
4677         }
4678
4679         logger = test_utils::TestLogger::new();
4680         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4681         persister = test_utils::TestPersister::new();
4682         let keys_manager = &chanmon_cfgs[0].keys_manager;
4683         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4684         nodes[0].chain_monitor = &new_chain_monitor;
4685
4686
4687         let mut node_0_stale_monitors = Vec::new();
4688         for serialized in node_0_stale_monitors_serialized.iter() {
4689                 let mut read = &serialized[..];
4690                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4691                 assert!(read.is_empty());
4692                 node_0_stale_monitors.push(monitor);
4693         }
4694
4695         let mut node_0_monitors = Vec::new();
4696         for serialized in node_0_monitors_serialized.iter() {
4697                 let mut read = &serialized[..];
4698                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4699                 assert!(read.is_empty());
4700                 node_0_monitors.push(monitor);
4701         }
4702
4703         let mut nodes_0_read = &nodes_0_serialized[..];
4704         if let Err(msgs::DecodeError::InvalidValue) =
4705                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4706                 default_config: UserConfig::default(),
4707                 keys_manager,
4708                 fee_estimator: &fee_estimator,
4709                 chain_monitor: nodes[0].chain_monitor,
4710                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4711                 logger: &logger,
4712                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4713         }) { } else {
4714                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4715         };
4716
4717         let mut nodes_0_read = &nodes_0_serialized[..];
4718         let (_, nodes_0_deserialized_tmp) =
4719                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4720                 default_config: UserConfig::default(),
4721                 keys_manager,
4722                 fee_estimator: &fee_estimator,
4723                 chain_monitor: nodes[0].chain_monitor,
4724                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4725                 logger: &logger,
4726                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4727         }).unwrap();
4728         nodes_0_deserialized = nodes_0_deserialized_tmp;
4729         assert!(nodes_0_read.is_empty());
4730
4731         { // Channel close should result in a commitment tx
4732                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4733                 assert_eq!(txn.len(), 1);
4734                 check_spends!(txn[0], funding_tx);
4735                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4736         }
4737
4738         for monitor in node_0_monitors.drain(..) {
4739                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4740                 check_added_monitors!(nodes[0], 1);
4741         }
4742         nodes[0].node = &nodes_0_deserialized;
4743         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4744
4745         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4746         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4747         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4748         //... and we can even still claim the payment!
4749         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4750
4751         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4752         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4753         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4754         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4755         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4756         assert_eq!(msg_events.len(), 1);
4757         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4758                 match action {
4759                         &ErrorAction::SendErrorMessage { ref msg } => {
4760                                 assert_eq!(msg.channel_id, channel_id);
4761                         },
4762                         _ => panic!("Unexpected event!"),
4763                 }
4764         }
4765 }
4766
4767 macro_rules! check_spendable_outputs {
4768         ($node: expr, $keysinterface: expr) => {
4769                 {
4770                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4771                         let mut txn = Vec::new();
4772                         let mut all_outputs = Vec::new();
4773                         let secp_ctx = Secp256k1::new();
4774                         for event in events.drain(..) {
4775                                 match event {
4776                                         Event::SpendableOutputs { mut outputs } => {
4777                                                 for outp in outputs.drain(..) {
4778                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4779                                                         all_outputs.push(outp);
4780                                                 }
4781                                         },
4782                                         _ => panic!("Unexpected event"),
4783                                 };
4784                         }
4785                         if all_outputs.len() > 1 {
4786                                 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) {
4787                                         txn.push(tx);
4788                                 }
4789                         }
4790                         txn
4791                 }
4792         }
4793 }
4794
4795 #[test]
4796 fn test_claim_sizeable_push_msat() {
4797         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4798         let chanmon_cfgs = create_chanmon_cfgs(2);
4799         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4800         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4801         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4802
4803         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4804         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4805         check_closed_broadcast!(nodes[1], true);
4806         check_added_monitors!(nodes[1], 1);
4807         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4808         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4809         assert_eq!(node_txn.len(), 1);
4810         check_spends!(node_txn[0], chan.3);
4811         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
4812
4813         mine_transaction(&nodes[1], &node_txn[0]);
4814         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4815
4816         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4817         assert_eq!(spend_txn.len(), 1);
4818         assert_eq!(spend_txn[0].input.len(), 1);
4819         check_spends!(spend_txn[0], node_txn[0]);
4820         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4821 }
4822
4823 #[test]
4824 fn test_claim_on_remote_sizeable_push_msat() {
4825         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4826         // to_remote output is encumbered by a P2WPKH
4827         let chanmon_cfgs = create_chanmon_cfgs(2);
4828         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4829         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4830         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4831
4832         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4833         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4834         check_closed_broadcast!(nodes[0], true);
4835         check_added_monitors!(nodes[0], 1);
4836         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4837
4838         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4839         assert_eq!(node_txn.len(), 1);
4840         check_spends!(node_txn[0], chan.3);
4841         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
4842
4843         mine_transaction(&nodes[1], &node_txn[0]);
4844         check_closed_broadcast!(nodes[1], true);
4845         check_added_monitors!(nodes[1], 1);
4846         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4847         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4848
4849         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4850         assert_eq!(spend_txn.len(), 1);
4851         check_spends!(spend_txn[0], node_txn[0]);
4852 }
4853
4854 #[test]
4855 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4856         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4857         // to_remote output is encumbered by a P2WPKH
4858
4859         let chanmon_cfgs = create_chanmon_cfgs(2);
4860         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4861         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4862         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4863
4864         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
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.2);
4867         assert_eq!(revoked_local_txn[0].input.len(), 1);
4868         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4869
4870         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4871         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4872         check_closed_broadcast!(nodes[1], true);
4873         check_added_monitors!(nodes[1], 1);
4874         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4875
4876         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4877         mine_transaction(&nodes[1], &node_txn[0]);
4878         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4879
4880         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4881         assert_eq!(spend_txn.len(), 3);
4882         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4883         check_spends!(spend_txn[1], node_txn[0]);
4884         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4885 }
4886
4887 #[test]
4888 fn test_static_spendable_outputs_preimage_tx() {
4889         let chanmon_cfgs = create_chanmon_cfgs(2);
4890         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4891         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4892         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4893
4894         // Create some initial channels
4895         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4896
4897         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4898
4899         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4900         assert_eq!(commitment_tx[0].input.len(), 1);
4901         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4902
4903         // Settle A's commitment tx on B's chain
4904         nodes[1].node.claim_funds(payment_preimage);
4905         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4906         check_added_monitors!(nodes[1], 1);
4907         mine_transaction(&nodes[1], &commitment_tx[0]);
4908         check_added_monitors!(nodes[1], 1);
4909         let events = nodes[1].node.get_and_clear_pending_msg_events();
4910         match events[0] {
4911                 MessageSendEvent::UpdateHTLCs { .. } => {},
4912                 _ => panic!("Unexpected event"),
4913         }
4914         match events[1] {
4915                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4916                 _ => panic!("Unexepected event"),
4917         }
4918
4919         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4920         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4921         assert_eq!(node_txn.len(), 3);
4922         check_spends!(node_txn[0], commitment_tx[0]);
4923         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4924         check_spends!(node_txn[1], chan_1.3);
4925         check_spends!(node_txn[2], node_txn[1]);
4926
4927         mine_transaction(&nodes[1], &node_txn[0]);
4928         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4929         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4930
4931         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4932         assert_eq!(spend_txn.len(), 1);
4933         check_spends!(spend_txn[0], node_txn[0]);
4934 }
4935
4936 #[test]
4937 fn test_static_spendable_outputs_timeout_tx() {
4938         let chanmon_cfgs = create_chanmon_cfgs(2);
4939         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4940         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4941         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4942
4943         // Create some initial channels
4944         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4945
4946         // Rebalance the network a bit by relaying one payment through all the channels ...
4947         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4948
4949         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4950
4951         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4952         assert_eq!(commitment_tx[0].input.len(), 1);
4953         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4954
4955         // Settle A's commitment tx on B' chain
4956         mine_transaction(&nodes[1], &commitment_tx[0]);
4957         check_added_monitors!(nodes[1], 1);
4958         let events = nodes[1].node.get_and_clear_pending_msg_events();
4959         match events[0] {
4960                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4961                 _ => panic!("Unexpected event"),
4962         }
4963         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4964
4965         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4966         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4967         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4968         check_spends!(node_txn[0], chan_1.3.clone());
4969         check_spends!(node_txn[1],  commitment_tx[0].clone());
4970         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4971
4972         mine_transaction(&nodes[1], &node_txn[1]);
4973         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4974         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4975         expect_payment_failed!(nodes[1], our_payment_hash, true);
4976
4977         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4978         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4979         check_spends!(spend_txn[0], commitment_tx[0]);
4980         check_spends!(spend_txn[1], node_txn[1]);
4981         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4982 }
4983
4984 #[test]
4985 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4986         let chanmon_cfgs = create_chanmon_cfgs(2);
4987         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4988         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4989         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4990
4991         // Create some initial channels
4992         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4993
4994         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4995         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4996         assert_eq!(revoked_local_txn[0].input.len(), 1);
4997         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4998
4999         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5000
5001         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5002         check_closed_broadcast!(nodes[1], true);
5003         check_added_monitors!(nodes[1], 1);
5004         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5005
5006         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5007         assert_eq!(node_txn.len(), 2);
5008         assert_eq!(node_txn[0].input.len(), 2);
5009         check_spends!(node_txn[0], revoked_local_txn[0]);
5010
5011         mine_transaction(&nodes[1], &node_txn[0]);
5012         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5013
5014         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5015         assert_eq!(spend_txn.len(), 1);
5016         check_spends!(spend_txn[0], node_txn[0]);
5017 }
5018
5019 #[test]
5020 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5021         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5022         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5023         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5024         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5025         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5026
5027         // Create some initial channels
5028         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5029
5030         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5031         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5032         assert_eq!(revoked_local_txn[0].input.len(), 1);
5033         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5034
5035         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5036
5037         // A will generate HTLC-Timeout from revoked commitment tx
5038         mine_transaction(&nodes[0], &revoked_local_txn[0]);
5039         check_closed_broadcast!(nodes[0], true);
5040         check_added_monitors!(nodes[0], 1);
5041         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5042         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5043
5044         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5045         assert_eq!(revoked_htlc_txn.len(), 2);
5046         check_spends!(revoked_htlc_txn[0], chan_1.3);
5047         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5048         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5049         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5050         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5051
5052         // B will generate justice tx from A's revoked commitment/HTLC tx
5053         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5054         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5055         check_closed_broadcast!(nodes[1], true);
5056         check_added_monitors!(nodes[1], 1);
5057         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5058
5059         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5060         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5061         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5062         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5063         // transactions next...
5064         assert_eq!(node_txn[0].input.len(), 3);
5065         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5066
5067         assert_eq!(node_txn[1].input.len(), 2);
5068         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5069         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5070                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5071         } else {
5072                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5073                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5074         }
5075
5076         assert_eq!(node_txn[2].input.len(), 1);
5077         check_spends!(node_txn[2], chan_1.3);
5078
5079         mine_transaction(&nodes[1], &node_txn[1]);
5080         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5081
5082         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5083         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5084         assert_eq!(spend_txn.len(), 1);
5085         assert_eq!(spend_txn[0].input.len(), 1);
5086         check_spends!(spend_txn[0], node_txn[1]);
5087 }
5088
5089 #[test]
5090 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5091         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5092         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5093         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5094         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5095         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5096
5097         // Create some initial channels
5098         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5099
5100         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5101         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5102         assert_eq!(revoked_local_txn[0].input.len(), 1);
5103         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5104
5105         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5106         assert_eq!(revoked_local_txn[0].output.len(), 2);
5107
5108         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5109
5110         // B will generate HTLC-Success from revoked commitment tx
5111         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5112         check_closed_broadcast!(nodes[1], true);
5113         check_added_monitors!(nodes[1], 1);
5114         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5115         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5116
5117         assert_eq!(revoked_htlc_txn.len(), 2);
5118         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5119         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5120         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5121
5122         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5123         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5124         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5125
5126         // A will generate justice tx from B's revoked commitment/HTLC tx
5127         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5128         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5129         check_closed_broadcast!(nodes[0], true);
5130         check_added_monitors!(nodes[0], 1);
5131         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5132
5133         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5134         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5135
5136         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5137         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5138         // transactions next...
5139         assert_eq!(node_txn[0].input.len(), 2);
5140         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5141         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5142                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5143         } else {
5144                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5145                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5146         }
5147
5148         assert_eq!(node_txn[1].input.len(), 1);
5149         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5150
5151         check_spends!(node_txn[2], chan_1.3);
5152
5153         mine_transaction(&nodes[0], &node_txn[1]);
5154         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5155
5156         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5157         // didn't try to generate any new transactions.
5158
5159         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5160         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5161         assert_eq!(spend_txn.len(), 3);
5162         assert_eq!(spend_txn[0].input.len(), 1);
5163         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5164         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5165         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5166         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5167 }
5168
5169 #[test]
5170 fn test_onchain_to_onchain_claim() {
5171         // Test that in case of channel closure, we detect the state of output and claim HTLC
5172         // on downstream peer's remote commitment tx.
5173         // First, have C claim an HTLC against its own latest commitment transaction.
5174         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5175         // channel.
5176         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5177         // gets broadcast.
5178
5179         let chanmon_cfgs = create_chanmon_cfgs(3);
5180         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5181         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5182         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5183
5184         // Create some initial channels
5185         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5186         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5187
5188         // Ensure all nodes are at the same height
5189         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5190         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5191         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5192         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5193
5194         // Rebalance the network a bit by relaying one payment through all the channels ...
5195         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5196         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5197
5198         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5199         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5200         check_spends!(commitment_tx[0], chan_2.3);
5201         nodes[2].node.claim_funds(payment_preimage);
5202         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5203         check_added_monitors!(nodes[2], 1);
5204         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5205         assert!(updates.update_add_htlcs.is_empty());
5206         assert!(updates.update_fail_htlcs.is_empty());
5207         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5208         assert!(updates.update_fail_malformed_htlcs.is_empty());
5209
5210         mine_transaction(&nodes[2], &commitment_tx[0]);
5211         check_closed_broadcast!(nodes[2], true);
5212         check_added_monitors!(nodes[2], 1);
5213         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5214
5215         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5216         assert_eq!(c_txn.len(), 3);
5217         assert_eq!(c_txn[0], c_txn[2]);
5218         assert_eq!(commitment_tx[0], c_txn[1]);
5219         check_spends!(c_txn[1], chan_2.3);
5220         check_spends!(c_txn[2], c_txn[1]);
5221         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5222         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5223         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5224         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5225
5226         // 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
5227         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5228         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5229         check_added_monitors!(nodes[1], 1);
5230         let events = nodes[1].node.get_and_clear_pending_events();
5231         assert_eq!(events.len(), 2);
5232         match events[0] {
5233                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5234                 _ => panic!("Unexpected event"),
5235         }
5236         match events[1] {
5237                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5238                         assert_eq!(fee_earned_msat, Some(1000));
5239                         assert_eq!(prev_channel_id, Some(chan_1.2));
5240                         assert_eq!(claim_from_onchain_tx, true);
5241                         assert_eq!(next_channel_id, Some(chan_2.2));
5242                 },
5243                 _ => panic!("Unexpected event"),
5244         }
5245         {
5246                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5247                 // ChannelMonitor: claim tx
5248                 assert_eq!(b_txn.len(), 1);
5249                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5250                 b_txn.clear();
5251         }
5252         check_added_monitors!(nodes[1], 1);
5253         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5254         assert_eq!(msg_events.len(), 3);
5255         match msg_events[0] {
5256                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5257                 _ => panic!("Unexpected event"),
5258         }
5259         match msg_events[1] {
5260                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5261                 _ => panic!("Unexpected event"),
5262         }
5263         match msg_events[2] {
5264                 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, .. } } => {
5265                         assert!(update_add_htlcs.is_empty());
5266                         assert!(update_fail_htlcs.is_empty());
5267                         assert_eq!(update_fulfill_htlcs.len(), 1);
5268                         assert!(update_fail_malformed_htlcs.is_empty());
5269                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5270                 },
5271                 _ => panic!("Unexpected event"),
5272         };
5273         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5274         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5275         mine_transaction(&nodes[1], &commitment_tx[0]);
5276         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5277         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5278         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5279         assert_eq!(b_txn.len(), 3);
5280         check_spends!(b_txn[1], chan_1.3);
5281         check_spends!(b_txn[2], b_txn[1]);
5282         check_spends!(b_txn[0], commitment_tx[0]);
5283         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5284         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5285         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5286
5287         check_closed_broadcast!(nodes[1], true);
5288         check_added_monitors!(nodes[1], 1);
5289 }
5290
5291 #[test]
5292 fn test_duplicate_payment_hash_one_failure_one_success() {
5293         // Topology : A --> B --> C --> D
5294         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5295         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5296         // we forward one of the payments onwards to D.
5297         let chanmon_cfgs = create_chanmon_cfgs(4);
5298         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5299         // When this test was written, the default base fee floated based on the HTLC count.
5300         // It is now fixed, so we simply set the fee to the expected value here.
5301         let mut config = test_default_channel_config();
5302         config.channel_config.forwarding_fee_base_msat = 196;
5303         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5304                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5305         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5306
5307         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5308         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5309         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5310
5311         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5312         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5313         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5314         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5315         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5316
5317         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5318
5319         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5320         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5321         // script push size limit so that the below script length checks match
5322         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5323         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5324                 .with_features(InvoiceFeatures::known());
5325         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5326         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5327
5328         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5329         assert_eq!(commitment_txn[0].input.len(), 1);
5330         check_spends!(commitment_txn[0], chan_2.3);
5331
5332         mine_transaction(&nodes[1], &commitment_txn[0]);
5333         check_closed_broadcast!(nodes[1], true);
5334         check_added_monitors!(nodes[1], 1);
5335         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5336         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5337
5338         let htlc_timeout_tx;
5339         { // Extract one of the two HTLC-Timeout transaction
5340                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5341                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5342                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5343                 check_spends!(node_txn[0], chan_2.3);
5344
5345                 check_spends!(node_txn[1], commitment_txn[0]);
5346                 assert_eq!(node_txn[1].input.len(), 1);
5347
5348                 if node_txn.len() > 3 {
5349                         check_spends!(node_txn[2], commitment_txn[0]);
5350                         assert_eq!(node_txn[2].input.len(), 1);
5351                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5352
5353                         check_spends!(node_txn[3], commitment_txn[0]);
5354                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5355                 } else {
5356                         check_spends!(node_txn[2], commitment_txn[0]);
5357                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5358                 }
5359
5360                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5361                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5362                 if node_txn.len() > 3 {
5363                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5364                 }
5365                 htlc_timeout_tx = node_txn[1].clone();
5366         }
5367
5368         nodes[2].node.claim_funds(our_payment_preimage);
5369         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5370
5371         mine_transaction(&nodes[2], &commitment_txn[0]);
5372         check_added_monitors!(nodes[2], 2);
5373         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5374         let events = nodes[2].node.get_and_clear_pending_msg_events();
5375         match events[0] {
5376                 MessageSendEvent::UpdateHTLCs { .. } => {},
5377                 _ => panic!("Unexpected event"),
5378         }
5379         match events[1] {
5380                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5381                 _ => panic!("Unexepected event"),
5382         }
5383         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5384         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)
5385         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5386         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5387         assert_eq!(htlc_success_txn[0].input.len(), 1);
5388         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5389         assert_eq!(htlc_success_txn[1].input.len(), 1);
5390         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5391         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5392         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5393         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5394         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5395         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5396
5397         mine_transaction(&nodes[1], &htlc_timeout_tx);
5398         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5399         expect_pending_htlcs_forwardable!(nodes[1]);
5400         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5401         assert!(htlc_updates.update_add_htlcs.is_empty());
5402         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5403         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5404         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5405         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5406         check_added_monitors!(nodes[1], 1);
5407
5408         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5409         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5410         {
5411                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5412         }
5413         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5414
5415         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5416         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5417         // and nodes[2] fee) is rounded down and then claimed in full.
5418         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5419         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5420         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5421         assert!(updates.update_add_htlcs.is_empty());
5422         assert!(updates.update_fail_htlcs.is_empty());
5423         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5424         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5425         assert!(updates.update_fail_malformed_htlcs.is_empty());
5426         check_added_monitors!(nodes[1], 1);
5427
5428         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5429         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5430
5431         let events = nodes[0].node.get_and_clear_pending_events();
5432         match events[0] {
5433                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5434                         assert_eq!(*payment_preimage, our_payment_preimage);
5435                         assert_eq!(*payment_hash, duplicate_payment_hash);
5436                 }
5437                 _ => panic!("Unexpected event"),
5438         }
5439 }
5440
5441 #[test]
5442 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5443         let chanmon_cfgs = create_chanmon_cfgs(2);
5444         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5445         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5446         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5447
5448         // Create some initial channels
5449         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5450
5451         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5452         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5453         assert_eq!(local_txn.len(), 1);
5454         assert_eq!(local_txn[0].input.len(), 1);
5455         check_spends!(local_txn[0], chan_1.3);
5456
5457         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5458         nodes[1].node.claim_funds(payment_preimage);
5459         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5460         check_added_monitors!(nodes[1], 1);
5461
5462         mine_transaction(&nodes[1], &local_txn[0]);
5463         check_added_monitors!(nodes[1], 1);
5464         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5465         let events = nodes[1].node.get_and_clear_pending_msg_events();
5466         match events[0] {
5467                 MessageSendEvent::UpdateHTLCs { .. } => {},
5468                 _ => panic!("Unexpected event"),
5469         }
5470         match events[1] {
5471                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5472                 _ => panic!("Unexepected event"),
5473         }
5474         let node_tx = {
5475                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5476                 assert_eq!(node_txn.len(), 3);
5477                 assert_eq!(node_txn[0], node_txn[2]);
5478                 assert_eq!(node_txn[1], local_txn[0]);
5479                 assert_eq!(node_txn[0].input.len(), 1);
5480                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5481                 check_spends!(node_txn[0], local_txn[0]);
5482                 node_txn[0].clone()
5483         };
5484
5485         mine_transaction(&nodes[1], &node_tx);
5486         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5487
5488         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5489         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5490         assert_eq!(spend_txn.len(), 1);
5491         assert_eq!(spend_txn[0].input.len(), 1);
5492         check_spends!(spend_txn[0], node_tx);
5493         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5494 }
5495
5496 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5497         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5498         // unrevoked commitment transaction.
5499         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5500         // a remote RAA before they could be failed backwards (and combinations thereof).
5501         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5502         // use the same payment hashes.
5503         // Thus, we use a six-node network:
5504         //
5505         // A \         / E
5506         //    - C - D -
5507         // B /         \ F
5508         // And test where C fails back to A/B when D announces its latest commitment transaction
5509         let chanmon_cfgs = create_chanmon_cfgs(6);
5510         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5511         // When this test was written, the default base fee floated based on the HTLC count.
5512         // It is now fixed, so we simply set the fee to the expected value here.
5513         let mut config = test_default_channel_config();
5514         config.channel_config.forwarding_fee_base_msat = 196;
5515         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5516                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5517         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5518
5519         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5520         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5521         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5522         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5523         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5524
5525         // Rebalance and check output sanity...
5526         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5527         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5528         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5529
5530         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5531         // 0th HTLC:
5532         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
5533         // 1st HTLC:
5534         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
5535         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5536         // 2nd HTLC:
5537         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
5538         // 3rd HTLC:
5539         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
5540         // 4th HTLC:
5541         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5542         // 5th HTLC:
5543         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5544         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5545         // 6th HTLC:
5546         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());
5547         // 7th HTLC:
5548         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());
5549
5550         // 8th HTLC:
5551         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5552         // 9th HTLC:
5553         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5554         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
5555
5556         // 10th HTLC:
5557         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
5558         // 11th HTLC:
5559         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5560         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());
5561
5562         // Double-check that six of the new HTLC were added
5563         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5564         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5565         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5566         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5567
5568         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5569         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5570         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5571         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5572         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5573         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5574         check_added_monitors!(nodes[4], 0);
5575         expect_pending_htlcs_forwardable!(nodes[4]);
5576         check_added_monitors!(nodes[4], 1);
5577
5578         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5579         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5580         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5581         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5582         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5583         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5584
5585         // Fail 3rd below-dust and 7th above-dust HTLCs
5586         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5587         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5588         check_added_monitors!(nodes[5], 0);
5589         expect_pending_htlcs_forwardable!(nodes[5]);
5590         check_added_monitors!(nodes[5], 1);
5591
5592         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5593         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5594         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5595         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5596
5597         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5598
5599         expect_pending_htlcs_forwardable!(nodes[3]);
5600         check_added_monitors!(nodes[3], 1);
5601         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5602         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5603         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5604         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5605         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5606         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5607         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5608         if deliver_last_raa {
5609                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5610         } else {
5611                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5612         }
5613
5614         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5615         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5616         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5617         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5618         //
5619         // We now broadcast the latest commitment transaction, which *should* result in failures for
5620         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5621         // the non-broadcast above-dust HTLCs.
5622         //
5623         // Alternatively, we may broadcast the previous commitment transaction, which should only
5624         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5625         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5626
5627         if announce_latest {
5628                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5629         } else {
5630                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5631         }
5632         let events = nodes[2].node.get_and_clear_pending_events();
5633         let close_event = if deliver_last_raa {
5634                 assert_eq!(events.len(), 2);
5635                 events[1].clone()
5636         } else {
5637                 assert_eq!(events.len(), 1);
5638                 events[0].clone()
5639         };
5640         match close_event {
5641                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5642                 _ => panic!("Unexpected event"),
5643         }
5644
5645         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5646         check_closed_broadcast!(nodes[2], true);
5647         if deliver_last_raa {
5648                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5649         } else {
5650                 expect_pending_htlcs_forwardable!(nodes[2]);
5651         }
5652         check_added_monitors!(nodes[2], 3);
5653
5654         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5655         assert_eq!(cs_msgs.len(), 2);
5656         let mut a_done = false;
5657         for msg in cs_msgs {
5658                 match msg {
5659                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5660                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5661                                 // should be failed-backwards here.
5662                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5663                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5664                                         for htlc in &updates.update_fail_htlcs {
5665                                                 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 });
5666                                         }
5667                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5668                                         assert!(!a_done);
5669                                         a_done = true;
5670                                         &nodes[0]
5671                                 } else {
5672                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5673                                         for htlc in &updates.update_fail_htlcs {
5674                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5675                                         }
5676                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5677                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5678                                         &nodes[1]
5679                                 };
5680                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5681                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5682                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5683                                 if announce_latest {
5684                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5685                                         if *node_id == nodes[0].node.get_our_node_id() {
5686                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5687                                         }
5688                                 }
5689                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5690                         },
5691                         _ => panic!("Unexpected event"),
5692                 }
5693         }
5694
5695         let as_events = nodes[0].node.get_and_clear_pending_events();
5696         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5697         let mut as_failds = HashSet::new();
5698         let mut as_updates = 0;
5699         for event in as_events.iter() {
5700                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5701                         assert!(as_failds.insert(*payment_hash));
5702                         if *payment_hash != payment_hash_2 {
5703                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5704                         } else {
5705                                 assert!(!rejected_by_dest);
5706                         }
5707                         if network_update.is_some() {
5708                                 as_updates += 1;
5709                         }
5710                 } else { panic!("Unexpected event"); }
5711         }
5712         assert!(as_failds.contains(&payment_hash_1));
5713         assert!(as_failds.contains(&payment_hash_2));
5714         if announce_latest {
5715                 assert!(as_failds.contains(&payment_hash_3));
5716                 assert!(as_failds.contains(&payment_hash_5));
5717         }
5718         assert!(as_failds.contains(&payment_hash_6));
5719
5720         let bs_events = nodes[1].node.get_and_clear_pending_events();
5721         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5722         let mut bs_failds = HashSet::new();
5723         let mut bs_updates = 0;
5724         for event in bs_events.iter() {
5725                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5726                         assert!(bs_failds.insert(*payment_hash));
5727                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5728                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5729                         } else {
5730                                 assert!(!rejected_by_dest);
5731                         }
5732                         if network_update.is_some() {
5733                                 bs_updates += 1;
5734                         }
5735                 } else { panic!("Unexpected event"); }
5736         }
5737         assert!(bs_failds.contains(&payment_hash_1));
5738         assert!(bs_failds.contains(&payment_hash_2));
5739         if announce_latest {
5740                 assert!(bs_failds.contains(&payment_hash_4));
5741         }
5742         assert!(bs_failds.contains(&payment_hash_5));
5743
5744         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5745         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5746         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5747         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5748         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5749         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5750 }
5751
5752 #[test]
5753 fn test_fail_backwards_latest_remote_announce_a() {
5754         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5755 }
5756
5757 #[test]
5758 fn test_fail_backwards_latest_remote_announce_b() {
5759         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5760 }
5761
5762 #[test]
5763 fn test_fail_backwards_previous_remote_announce() {
5764         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5765         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5766         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5767 }
5768
5769 #[test]
5770 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5771         let chanmon_cfgs = create_chanmon_cfgs(2);
5772         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5773         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5774         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5775
5776         // Create some initial channels
5777         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5778
5779         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5780         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5781         assert_eq!(local_txn[0].input.len(), 1);
5782         check_spends!(local_txn[0], chan_1.3);
5783
5784         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5785         mine_transaction(&nodes[0], &local_txn[0]);
5786         check_closed_broadcast!(nodes[0], true);
5787         check_added_monitors!(nodes[0], 1);
5788         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5789         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5790
5791         let htlc_timeout = {
5792                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5793                 assert_eq!(node_txn.len(), 2);
5794                 check_spends!(node_txn[0], chan_1.3);
5795                 assert_eq!(node_txn[1].input.len(), 1);
5796                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5797                 check_spends!(node_txn[1], local_txn[0]);
5798                 node_txn[1].clone()
5799         };
5800
5801         mine_transaction(&nodes[0], &htlc_timeout);
5802         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5803         expect_payment_failed!(nodes[0], our_payment_hash, true);
5804
5805         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5806         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5807         assert_eq!(spend_txn.len(), 3);
5808         check_spends!(spend_txn[0], local_txn[0]);
5809         assert_eq!(spend_txn[1].input.len(), 1);
5810         check_spends!(spend_txn[1], htlc_timeout);
5811         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5812         assert_eq!(spend_txn[2].input.len(), 2);
5813         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5814         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5815                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5816 }
5817
5818 #[test]
5819 fn test_key_derivation_params() {
5820         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5821         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5822         // let us re-derive the channel key set to then derive a delayed_payment_key.
5823
5824         let chanmon_cfgs = create_chanmon_cfgs(3);
5825
5826         // We manually create the node configuration to backup the seed.
5827         let seed = [42; 32];
5828         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5829         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);
5830         let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5831         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, node_seed: seed, features: InitFeatures::known() };
5832         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5833         node_cfgs.remove(0);
5834         node_cfgs.insert(0, node);
5835
5836         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5837         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5838
5839         // Create some initial channels
5840         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5841         // for node 0
5842         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5843         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5844         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5845
5846         // Ensure all nodes are at the same height
5847         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5848         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5849         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5850         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5851
5852         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5853         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5854         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5855         assert_eq!(local_txn_1[0].input.len(), 1);
5856         check_spends!(local_txn_1[0], chan_1.3);
5857
5858         // We check funding pubkey are unique
5859         let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][36..69]));
5860         let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][36..69]));
5861         if from_0_funding_key_0 == from_1_funding_key_0
5862             || from_0_funding_key_0 == from_1_funding_key_1
5863             || from_0_funding_key_1 == from_1_funding_key_0
5864             || from_0_funding_key_1 == from_1_funding_key_1 {
5865                 panic!("Funding pubkeys aren't unique");
5866         }
5867
5868         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5869         mine_transaction(&nodes[0], &local_txn_1[0]);
5870         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5871         check_closed_broadcast!(nodes[0], true);
5872         check_added_monitors!(nodes[0], 1);
5873         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5874
5875         let htlc_timeout = {
5876                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5877                 assert_eq!(node_txn[1].input.len(), 1);
5878                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5879                 check_spends!(node_txn[1], local_txn_1[0]);
5880                 node_txn[1].clone()
5881         };
5882
5883         mine_transaction(&nodes[0], &htlc_timeout);
5884         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5885         expect_payment_failed!(nodes[0], our_payment_hash, true);
5886
5887         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5888         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5889         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5890         assert_eq!(spend_txn.len(), 3);
5891         check_spends!(spend_txn[0], local_txn_1[0]);
5892         assert_eq!(spend_txn[1].input.len(), 1);
5893         check_spends!(spend_txn[1], htlc_timeout);
5894         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5895         assert_eq!(spend_txn[2].input.len(), 2);
5896         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5897         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5898                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5899 }
5900
5901 #[test]
5902 fn test_static_output_closing_tx() {
5903         let chanmon_cfgs = create_chanmon_cfgs(2);
5904         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5905         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5906         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5907
5908         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5909
5910         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5911         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5912
5913         mine_transaction(&nodes[0], &closing_tx);
5914         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5915         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5916
5917         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5918         assert_eq!(spend_txn.len(), 1);
5919         check_spends!(spend_txn[0], closing_tx);
5920
5921         mine_transaction(&nodes[1], &closing_tx);
5922         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5923         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5924
5925         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5926         assert_eq!(spend_txn.len(), 1);
5927         check_spends!(spend_txn[0], closing_tx);
5928 }
5929
5930 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5931         let chanmon_cfgs = create_chanmon_cfgs(2);
5932         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5933         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5934         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5935         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5936
5937         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5938
5939         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5940         // present in B's local commitment transaction, but none of A's commitment transactions.
5941         nodes[1].node.claim_funds(payment_preimage);
5942         check_added_monitors!(nodes[1], 1);
5943         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5944
5945         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5946         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5947         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5948
5949         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5950         check_added_monitors!(nodes[0], 1);
5951         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5952         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5953         check_added_monitors!(nodes[1], 1);
5954
5955         let starting_block = nodes[1].best_block_info();
5956         let mut block = Block {
5957                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5958                 txdata: vec![],
5959         };
5960         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5961                 connect_block(&nodes[1], &block);
5962                 block.header.prev_blockhash = block.block_hash();
5963         }
5964         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5965         check_closed_broadcast!(nodes[1], true);
5966         check_added_monitors!(nodes[1], 1);
5967         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5968 }
5969
5970 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5971         let chanmon_cfgs = create_chanmon_cfgs(2);
5972         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5973         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5974         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5975         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5976
5977         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5978         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5979         check_added_monitors!(nodes[0], 1);
5980
5981         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5982
5983         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5984         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5985         // to "time out" the HTLC.
5986
5987         let starting_block = nodes[1].best_block_info();
5988         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5989
5990         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5991                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5992                 header.prev_blockhash = header.block_hash();
5993         }
5994         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5995         check_closed_broadcast!(nodes[0], true);
5996         check_added_monitors!(nodes[0], 1);
5997         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5998 }
5999
6000 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
6001         let chanmon_cfgs = create_chanmon_cfgs(3);
6002         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6003         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6004         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6005         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6006
6007         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6008         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6009         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6010         // actually revoked.
6011         let htlc_value = if use_dust { 50000 } else { 3000000 };
6012         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6013         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6014         expect_pending_htlcs_forwardable!(nodes[1]);
6015         check_added_monitors!(nodes[1], 1);
6016
6017         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6018         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6019         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6020         check_added_monitors!(nodes[0], 1);
6021         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6022         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6023         check_added_monitors!(nodes[1], 1);
6024         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6025         check_added_monitors!(nodes[1], 1);
6026         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6027
6028         if check_revoke_no_close {
6029                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6030                 check_added_monitors!(nodes[0], 1);
6031         }
6032
6033         let starting_block = nodes[1].best_block_info();
6034         let mut block = Block {
6035                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6036                 txdata: vec![],
6037         };
6038         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6039                 connect_block(&nodes[0], &block);
6040                 block.header.prev_blockhash = block.block_hash();
6041         }
6042         if !check_revoke_no_close {
6043                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6044                 check_closed_broadcast!(nodes[0], true);
6045                 check_added_monitors!(nodes[0], 1);
6046                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6047         } else {
6048                 let events = nodes[0].node.get_and_clear_pending_events();
6049                 assert_eq!(events.len(), 2);
6050                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6051                         assert_eq!(*payment_hash, our_payment_hash);
6052                 } else { panic!("Unexpected event"); }
6053                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6054                         assert_eq!(*payment_hash, our_payment_hash);
6055                 } else { panic!("Unexpected event"); }
6056         }
6057 }
6058
6059 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6060 // There are only a few cases to test here:
6061 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
6062 //    broadcastable commitment transactions result in channel closure,
6063 //  * its included in an unrevoked-but-previous remote commitment transaction,
6064 //  * its included in the latest remote or local commitment transactions.
6065 // We test each of the three possible commitment transactions individually and use both dust and
6066 // non-dust HTLCs.
6067 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6068 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6069 // tested for at least one of the cases in other tests.
6070 #[test]
6071 fn htlc_claim_single_commitment_only_a() {
6072         do_htlc_claim_local_commitment_only(true);
6073         do_htlc_claim_local_commitment_only(false);
6074
6075         do_htlc_claim_current_remote_commitment_only(true);
6076         do_htlc_claim_current_remote_commitment_only(false);
6077 }
6078
6079 #[test]
6080 fn htlc_claim_single_commitment_only_b() {
6081         do_htlc_claim_previous_remote_commitment_only(true, false);
6082         do_htlc_claim_previous_remote_commitment_only(false, false);
6083         do_htlc_claim_previous_remote_commitment_only(true, true);
6084         do_htlc_claim_previous_remote_commitment_only(false, true);
6085 }
6086
6087 #[test]
6088 #[should_panic]
6089 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6090         let chanmon_cfgs = create_chanmon_cfgs(2);
6091         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6092         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6093         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6094         // Force duplicate randomness for every get-random call
6095         for node in nodes.iter() {
6096                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6097         }
6098
6099         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6100         let channel_value_satoshis=10000;
6101         let push_msat=10001;
6102         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6103         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6104         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6105         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6106
6107         // Create a second channel with the same random values. This used to panic due to a colliding
6108         // channel_id, but now panics due to a colliding outbound SCID alias.
6109         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6110 }
6111
6112 #[test]
6113 fn bolt2_open_channel_sending_node_checks_part2() {
6114         let chanmon_cfgs = create_chanmon_cfgs(2);
6115         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6116         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6117         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6118
6119         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6120         let channel_value_satoshis=2^24;
6121         let push_msat=10001;
6122         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6123
6124         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6125         let channel_value_satoshis=10000;
6126         // Test when push_msat is equal to 1000 * funding_satoshis.
6127         let push_msat=1000*channel_value_satoshis+1;
6128         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6129
6130         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6131         let channel_value_satoshis=10000;
6132         let push_msat=10001;
6133         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
6134         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6135         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6136
6137         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6138         // 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
6139         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6140
6141         // 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.
6142         assert!(BREAKDOWN_TIMEOUT>0);
6143         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6144
6145         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6146         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6147         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6148
6149         // 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.
6150         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6151         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6152         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6153         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6154         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6155 }
6156
6157 #[test]
6158 fn bolt2_open_channel_sane_dust_limit() {
6159         let chanmon_cfgs = create_chanmon_cfgs(2);
6160         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6161         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6162         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6163
6164         let channel_value_satoshis=1000000;
6165         let push_msat=10001;
6166         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6167         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6168         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6169         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6170
6171         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6172         let events = nodes[1].node.get_and_clear_pending_msg_events();
6173         let err_msg = match events[0] {
6174                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6175                         msg.clone()
6176                 },
6177                 _ => panic!("Unexpected event"),
6178         };
6179         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6180 }
6181
6182 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6183 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6184 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6185 // is no longer affordable once it's freed.
6186 #[test]
6187 fn test_fail_holding_cell_htlc_upon_free() {
6188         let chanmon_cfgs = create_chanmon_cfgs(2);
6189         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6190         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6191         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6192         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6193
6194         // First nodes[0] generates an update_fee, setting the channel's
6195         // pending_update_fee.
6196         {
6197                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6198                 *feerate_lock += 20;
6199         }
6200         nodes[0].node.timer_tick_occurred();
6201         check_added_monitors!(nodes[0], 1);
6202
6203         let events = nodes[0].node.get_and_clear_pending_msg_events();
6204         assert_eq!(events.len(), 1);
6205         let (update_msg, commitment_signed) = match events[0] {
6206                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6207                         (update_fee.as_ref(), commitment_signed)
6208                 },
6209                 _ => panic!("Unexpected event"),
6210         };
6211
6212         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6213
6214         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6215         let channel_reserve = chan_stat.channel_reserve_msat;
6216         let feerate = get_feerate!(nodes[0], chan.2);
6217         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6218
6219         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6220         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6221         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6222
6223         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6224         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6225         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6226         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6227
6228         // Flush the pending fee update.
6229         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6230         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6231         check_added_monitors!(nodes[1], 1);
6232         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6233         check_added_monitors!(nodes[0], 1);
6234
6235         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6236         // HTLC, but now that the fee has been raised the payment will now fail, causing
6237         // us to surface its failure to the user.
6238         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6239         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6240         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);
6241         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 {}",
6242                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6243         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6244
6245         // Check that the payment failed to be sent out.
6246         let events = nodes[0].node.get_and_clear_pending_events();
6247         assert_eq!(events.len(), 1);
6248         match &events[0] {
6249                 &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, .. } => {
6250                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6251                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6252                         assert_eq!(*rejected_by_dest, false);
6253                         assert_eq!(*all_paths_failed, true);
6254                         assert_eq!(*network_update, None);
6255                         assert_eq!(*short_channel_id, None);
6256                         assert_eq!(*error_code, None);
6257                         assert_eq!(*error_data, None);
6258                 },
6259                 _ => panic!("Unexpected event"),
6260         }
6261 }
6262
6263 // Test that if multiple HTLCs are released from the holding cell and one is
6264 // valid but the other is no longer valid upon release, the valid HTLC can be
6265 // successfully completed while the other one fails as expected.
6266 #[test]
6267 fn test_free_and_fail_holding_cell_htlcs() {
6268         let chanmon_cfgs = create_chanmon_cfgs(2);
6269         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6270         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6271         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6272         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6273
6274         // First nodes[0] generates an update_fee, setting the channel's
6275         // pending_update_fee.
6276         {
6277                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6278                 *feerate_lock += 200;
6279         }
6280         nodes[0].node.timer_tick_occurred();
6281         check_added_monitors!(nodes[0], 1);
6282
6283         let events = nodes[0].node.get_and_clear_pending_msg_events();
6284         assert_eq!(events.len(), 1);
6285         let (update_msg, commitment_signed) = match events[0] {
6286                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6287                         (update_fee.as_ref(), commitment_signed)
6288                 },
6289                 _ => panic!("Unexpected event"),
6290         };
6291
6292         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6293
6294         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6295         let channel_reserve = chan_stat.channel_reserve_msat;
6296         let feerate = get_feerate!(nodes[0], chan.2);
6297         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6298
6299         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6300         let amt_1 = 20000;
6301         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6302         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6303         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6304
6305         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6306         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6307         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6308         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6309         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6310         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6311         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6312
6313         // Flush the pending fee update.
6314         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6315         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6316         check_added_monitors!(nodes[1], 1);
6317         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6318         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6319         check_added_monitors!(nodes[0], 2);
6320
6321         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6322         // but now that the fee has been raised the second payment will now fail, causing us
6323         // to surface its failure to the user. The first payment should succeed.
6324         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6325         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6326         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);
6327         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 {}",
6328                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6329         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6330
6331         // Check that the second payment failed to be sent out.
6332         let events = nodes[0].node.get_and_clear_pending_events();
6333         assert_eq!(events.len(), 1);
6334         match &events[0] {
6335                 &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, .. } => {
6336                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6337                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6338                         assert_eq!(*rejected_by_dest, false);
6339                         assert_eq!(*all_paths_failed, true);
6340                         assert_eq!(*network_update, None);
6341                         assert_eq!(*short_channel_id, None);
6342                         assert_eq!(*error_code, None);
6343                         assert_eq!(*error_data, None);
6344                 },
6345                 _ => panic!("Unexpected event"),
6346         }
6347
6348         // Complete the first payment and the RAA from the fee update.
6349         let (payment_event, send_raa_event) = {
6350                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6351                 assert_eq!(msgs.len(), 2);
6352                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6353         };
6354         let raa = match send_raa_event {
6355                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6356                 _ => panic!("Unexpected event"),
6357         };
6358         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6359         check_added_monitors!(nodes[1], 1);
6360         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6361         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6362         let events = nodes[1].node.get_and_clear_pending_events();
6363         assert_eq!(events.len(), 1);
6364         match events[0] {
6365                 Event::PendingHTLCsForwardable { .. } => {},
6366                 _ => panic!("Unexpected event"),
6367         }
6368         nodes[1].node.process_pending_htlc_forwards();
6369         let events = nodes[1].node.get_and_clear_pending_events();
6370         assert_eq!(events.len(), 1);
6371         match events[0] {
6372                 Event::PaymentReceived { .. } => {},
6373                 _ => panic!("Unexpected event"),
6374         }
6375         nodes[1].node.claim_funds(payment_preimage_1);
6376         check_added_monitors!(nodes[1], 1);
6377         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6378
6379         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6380         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6381         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6382         expect_payment_sent!(nodes[0], payment_preimage_1);
6383 }
6384
6385 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6386 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6387 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6388 // once it's freed.
6389 #[test]
6390 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6391         let chanmon_cfgs = create_chanmon_cfgs(3);
6392         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6393         // When this test was written, the default base fee floated based on the HTLC count.
6394         // It is now fixed, so we simply set the fee to the expected value here.
6395         let mut config = test_default_channel_config();
6396         config.channel_config.forwarding_fee_base_msat = 196;
6397         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6398         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6399         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6400         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6401
6402         // First nodes[1] generates an update_fee, setting the channel's
6403         // pending_update_fee.
6404         {
6405                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6406                 *feerate_lock += 20;
6407         }
6408         nodes[1].node.timer_tick_occurred();
6409         check_added_monitors!(nodes[1], 1);
6410
6411         let events = nodes[1].node.get_and_clear_pending_msg_events();
6412         assert_eq!(events.len(), 1);
6413         let (update_msg, commitment_signed) = match events[0] {
6414                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6415                         (update_fee.as_ref(), commitment_signed)
6416                 },
6417                 _ => panic!("Unexpected event"),
6418         };
6419
6420         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6421
6422         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6423         let channel_reserve = chan_stat.channel_reserve_msat;
6424         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6425         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6426
6427         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6428         let feemsat = 239;
6429         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6430         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6431         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6432         let payment_event = {
6433                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6434                 check_added_monitors!(nodes[0], 1);
6435
6436                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6437                 assert_eq!(events.len(), 1);
6438
6439                 SendEvent::from_event(events.remove(0))
6440         };
6441         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6442         check_added_monitors!(nodes[1], 0);
6443         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6444         expect_pending_htlcs_forwardable!(nodes[1]);
6445
6446         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6447         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6448
6449         // Flush the pending fee update.
6450         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6451         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6452         check_added_monitors!(nodes[2], 1);
6453         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6454         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6455         check_added_monitors!(nodes[1], 2);
6456
6457         // A final RAA message is generated to finalize the fee update.
6458         let events = nodes[1].node.get_and_clear_pending_msg_events();
6459         assert_eq!(events.len(), 1);
6460
6461         let raa_msg = match &events[0] {
6462                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6463                         msg.clone()
6464                 },
6465                 _ => panic!("Unexpected event"),
6466         };
6467
6468         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6469         check_added_monitors!(nodes[2], 1);
6470         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6471
6472         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6473         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6474         assert_eq!(process_htlc_forwards_event.len(), 1);
6475         match &process_htlc_forwards_event[0] {
6476                 &Event::PendingHTLCsForwardable { .. } => {},
6477                 _ => panic!("Unexpected event"),
6478         }
6479
6480         // In response, we call ChannelManager's process_pending_htlc_forwards
6481         nodes[1].node.process_pending_htlc_forwards();
6482         check_added_monitors!(nodes[1], 1);
6483
6484         // This causes the HTLC to be failed backwards.
6485         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6486         assert_eq!(fail_event.len(), 1);
6487         let (fail_msg, commitment_signed) = match &fail_event[0] {
6488                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6489                         assert_eq!(updates.update_add_htlcs.len(), 0);
6490                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6491                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6492                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6493                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6494                 },
6495                 _ => panic!("Unexpected event"),
6496         };
6497
6498         // Pass the failure messages back to nodes[0].
6499         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6500         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6501
6502         // Complete the HTLC failure+removal process.
6503         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6504         check_added_monitors!(nodes[0], 1);
6505         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6506         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6507         check_added_monitors!(nodes[1], 2);
6508         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6509         assert_eq!(final_raa_event.len(), 1);
6510         let raa = match &final_raa_event[0] {
6511                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6512                 _ => panic!("Unexpected event"),
6513         };
6514         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6515         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6516         check_added_monitors!(nodes[0], 1);
6517 }
6518
6519 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6520 // 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.
6521 //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.
6522
6523 #[test]
6524 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6525         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6526         let chanmon_cfgs = create_chanmon_cfgs(2);
6527         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6528         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6529         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6530         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6531
6532         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6533         route.paths[0][0].fee_msat = 100;
6534
6535         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6536                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6537         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6538         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6539 }
6540
6541 #[test]
6542 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6543         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6544         let chanmon_cfgs = create_chanmon_cfgs(2);
6545         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6546         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6547         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6548         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6549
6550         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6551         route.paths[0][0].fee_msat = 0;
6552         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6553                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6554
6555         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6556         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6557 }
6558
6559 #[test]
6560 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6561         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6562         let chanmon_cfgs = create_chanmon_cfgs(2);
6563         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6564         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6565         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6566         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6567
6568         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6569         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6570         check_added_monitors!(nodes[0], 1);
6571         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6572         updates.update_add_htlcs[0].amount_msat = 0;
6573
6574         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6575         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6576         check_closed_broadcast!(nodes[1], true).unwrap();
6577         check_added_monitors!(nodes[1], 1);
6578         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6579 }
6580
6581 #[test]
6582 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6583         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6584         //It is enforced when constructing a route.
6585         let chanmon_cfgs = create_chanmon_cfgs(2);
6586         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6587         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6588         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6589         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6590
6591         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6592                 .with_features(InvoiceFeatures::known());
6593         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6594         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6595         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6596                 assert_eq!(err, &"Channel CLTV overflowed?"));
6597 }
6598
6599 #[test]
6600 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6601         //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.
6602         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6603         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6604         let chanmon_cfgs = create_chanmon_cfgs(2);
6605         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6606         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6607         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6608         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6609         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6610
6611         for i in 0..max_accepted_htlcs {
6612                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6613                 let payment_event = {
6614                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6615                         check_added_monitors!(nodes[0], 1);
6616
6617                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6618                         assert_eq!(events.len(), 1);
6619                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6620                                 assert_eq!(htlcs[0].htlc_id, i);
6621                         } else {
6622                                 assert!(false);
6623                         }
6624                         SendEvent::from_event(events.remove(0))
6625                 };
6626                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6627                 check_added_monitors!(nodes[1], 0);
6628                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6629
6630                 expect_pending_htlcs_forwardable!(nodes[1]);
6631                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6632         }
6633         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6634         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6635                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6636
6637         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6638         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6639 }
6640
6641 #[test]
6642 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6643         //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.
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         let channel_value = 100000;
6649         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6650         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6651
6652         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6653
6654         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6655         // Manually create a route over our max in flight (which our router normally automatically
6656         // limits us to.
6657         route.paths[0][0].fee_msat =  max_in_flight + 1;
6658         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6659                 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)));
6660
6661         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6662         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);
6663
6664         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6665 }
6666
6667 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6668 #[test]
6669 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6670         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6671         let chanmon_cfgs = create_chanmon_cfgs(2);
6672         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6673         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6674         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6675         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6676         let htlc_minimum_msat: u64;
6677         {
6678                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6679                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6680                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6681         }
6682
6683         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6684         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6685         check_added_monitors!(nodes[0], 1);
6686         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6687         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6688         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6689         assert!(nodes[1].node.list_channels().is_empty());
6690         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6691         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()));
6692         check_added_monitors!(nodes[1], 1);
6693         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6694 }
6695
6696 #[test]
6697 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6698         //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
6699         let chanmon_cfgs = create_chanmon_cfgs(2);
6700         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6701         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6702         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6703         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6704
6705         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6706         let channel_reserve = chan_stat.channel_reserve_msat;
6707         let feerate = get_feerate!(nodes[0], chan.2);
6708         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6709         // The 2* and +1 are for the fee spike reserve.
6710         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6711
6712         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6713         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6714         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6715         check_added_monitors!(nodes[0], 1);
6716         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6717
6718         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6719         // at this time channel-initiatee receivers are not required to enforce that senders
6720         // respect the fee_spike_reserve.
6721         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6722         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6723
6724         assert!(nodes[1].node.list_channels().is_empty());
6725         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6726         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6727         check_added_monitors!(nodes[1], 1);
6728         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6729 }
6730
6731 #[test]
6732 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6733         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6734         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6735         let chanmon_cfgs = create_chanmon_cfgs(2);
6736         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6737         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6738         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6739         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6740
6741         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6742         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6743         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6744         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6745         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6746         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6747
6748         let mut msg = msgs::UpdateAddHTLC {
6749                 channel_id: chan.2,
6750                 htlc_id: 0,
6751                 amount_msat: 1000,
6752                 payment_hash: our_payment_hash,
6753                 cltv_expiry: htlc_cltv,
6754                 onion_routing_packet: onion_packet.clone(),
6755         };
6756
6757         for i in 0..super::channel::OUR_MAX_HTLCS {
6758                 msg.htlc_id = i as u64;
6759                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6760         }
6761         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6762         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6763
6764         assert!(nodes[1].node.list_channels().is_empty());
6765         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6766         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6767         check_added_monitors!(nodes[1], 1);
6768         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6769 }
6770
6771 #[test]
6772 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6773         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6774         let chanmon_cfgs = create_chanmon_cfgs(2);
6775         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6776         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6777         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6778         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6779
6780         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6781         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6782         check_added_monitors!(nodes[0], 1);
6783         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6784         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6785         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6786
6787         assert!(nodes[1].node.list_channels().is_empty());
6788         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6789         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6790         check_added_monitors!(nodes[1], 1);
6791         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6792 }
6793
6794 #[test]
6795 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6796         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6797         let chanmon_cfgs = create_chanmon_cfgs(2);
6798         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6799         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6800         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6801
6802         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6803         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6804         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6805         check_added_monitors!(nodes[0], 1);
6806         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6807         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6808         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6809
6810         assert!(nodes[1].node.list_channels().is_empty());
6811         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6812         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6813         check_added_monitors!(nodes[1], 1);
6814         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6815 }
6816
6817 #[test]
6818 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6819         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6820         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6821         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6822         let chanmon_cfgs = create_chanmon_cfgs(2);
6823         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6824         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6825         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6826
6827         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6828         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6829         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6830         check_added_monitors!(nodes[0], 1);
6831         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6832         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6833
6834         //Disconnect and Reconnect
6835         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6836         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6837         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6838         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6839         assert_eq!(reestablish_1.len(), 1);
6840         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6841         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6842         assert_eq!(reestablish_2.len(), 1);
6843         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6844         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6845         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6846         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6847
6848         //Resend HTLC
6849         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6850         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6851         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6852         check_added_monitors!(nodes[1], 1);
6853         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6854
6855         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6856
6857         assert!(nodes[1].node.list_channels().is_empty());
6858         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6859         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6860         check_added_monitors!(nodes[1], 1);
6861         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6862 }
6863
6864 #[test]
6865 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6866         //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.
6867
6868         let chanmon_cfgs = create_chanmon_cfgs(2);
6869         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6870         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6871         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6872         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6873         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6874         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6875
6876         check_added_monitors!(nodes[0], 1);
6877         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6878         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6879
6880         let update_msg = msgs::UpdateFulfillHTLC{
6881                 channel_id: chan.2,
6882                 htlc_id: 0,
6883                 payment_preimage: our_payment_preimage,
6884         };
6885
6886         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6887
6888         assert!(nodes[0].node.list_channels().is_empty());
6889         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6890         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()));
6891         check_added_monitors!(nodes[0], 1);
6892         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6893 }
6894
6895 #[test]
6896 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6897         //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.
6898
6899         let chanmon_cfgs = create_chanmon_cfgs(2);
6900         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6901         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6902         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6903         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6904
6905         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6906         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6907         check_added_monitors!(nodes[0], 1);
6908         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6909         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6910
6911         let update_msg = msgs::UpdateFailHTLC{
6912                 channel_id: chan.2,
6913                 htlc_id: 0,
6914                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6915         };
6916
6917         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6918
6919         assert!(nodes[0].node.list_channels().is_empty());
6920         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6921         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()));
6922         check_added_monitors!(nodes[0], 1);
6923         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6924 }
6925
6926 #[test]
6927 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6928         //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.
6929
6930         let chanmon_cfgs = create_chanmon_cfgs(2);
6931         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6932         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6933         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6934         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6935
6936         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6937         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6938         check_added_monitors!(nodes[0], 1);
6939         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6940         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6941         let update_msg = msgs::UpdateFailMalformedHTLC{
6942                 channel_id: chan.2,
6943                 htlc_id: 0,
6944                 sha256_of_onion: [1; 32],
6945                 failure_code: 0x8000,
6946         };
6947
6948         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6949
6950         assert!(nodes[0].node.list_channels().is_empty());
6951         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6952         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()));
6953         check_added_monitors!(nodes[0], 1);
6954         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6955 }
6956
6957 #[test]
6958 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6959         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6960
6961         let chanmon_cfgs = create_chanmon_cfgs(2);
6962         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6963         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6964         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6965         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6966
6967         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6968
6969         nodes[1].node.claim_funds(our_payment_preimage);
6970         check_added_monitors!(nodes[1], 1);
6971         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6972
6973         let events = nodes[1].node.get_and_clear_pending_msg_events();
6974         assert_eq!(events.len(), 1);
6975         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6976                 match events[0] {
6977                         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, .. } } => {
6978                                 assert!(update_add_htlcs.is_empty());
6979                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6980                                 assert!(update_fail_htlcs.is_empty());
6981                                 assert!(update_fail_malformed_htlcs.is_empty());
6982                                 assert!(update_fee.is_none());
6983                                 update_fulfill_htlcs[0].clone()
6984                         },
6985                         _ => panic!("Unexpected event"),
6986                 }
6987         };
6988
6989         update_fulfill_msg.htlc_id = 1;
6990
6991         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6992
6993         assert!(nodes[0].node.list_channels().is_empty());
6994         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6995         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6996         check_added_monitors!(nodes[0], 1);
6997         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6998 }
6999
7000 #[test]
7001 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
7002         //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.
7003
7004         let chanmon_cfgs = create_chanmon_cfgs(2);
7005         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7006         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7007         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7008         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7009
7010         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
7011
7012         nodes[1].node.claim_funds(our_payment_preimage);
7013         check_added_monitors!(nodes[1], 1);
7014         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7015
7016         let events = nodes[1].node.get_and_clear_pending_msg_events();
7017         assert_eq!(events.len(), 1);
7018         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7019                 match events[0] {
7020                         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, .. } } => {
7021                                 assert!(update_add_htlcs.is_empty());
7022                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7023                                 assert!(update_fail_htlcs.is_empty());
7024                                 assert!(update_fail_malformed_htlcs.is_empty());
7025                                 assert!(update_fee.is_none());
7026                                 update_fulfill_htlcs[0].clone()
7027                         },
7028                         _ => panic!("Unexpected event"),
7029                 }
7030         };
7031
7032         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7033
7034         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7035
7036         assert!(nodes[0].node.list_channels().is_empty());
7037         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7038         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7039         check_added_monitors!(nodes[0], 1);
7040         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7041 }
7042
7043 #[test]
7044 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7045         //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.
7046
7047         let chanmon_cfgs = create_chanmon_cfgs(2);
7048         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7049         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7050         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7051         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7052
7053         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7054         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7055         check_added_monitors!(nodes[0], 1);
7056
7057         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7058         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7059
7060         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7061         check_added_monitors!(nodes[1], 0);
7062         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7063
7064         let events = nodes[1].node.get_and_clear_pending_msg_events();
7065
7066         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7067                 match events[0] {
7068                         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, .. } } => {
7069                                 assert!(update_add_htlcs.is_empty());
7070                                 assert!(update_fulfill_htlcs.is_empty());
7071                                 assert!(update_fail_htlcs.is_empty());
7072                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7073                                 assert!(update_fee.is_none());
7074                                 update_fail_malformed_htlcs[0].clone()
7075                         },
7076                         _ => panic!("Unexpected event"),
7077                 }
7078         };
7079         update_msg.failure_code &= !0x8000;
7080         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7081
7082         assert!(nodes[0].node.list_channels().is_empty());
7083         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7084         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7085         check_added_monitors!(nodes[0], 1);
7086         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7087 }
7088
7089 #[test]
7090 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7091         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7092         //    * 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.
7093
7094         let chanmon_cfgs = create_chanmon_cfgs(3);
7095         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7096         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7097         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7098         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7099         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7100
7101         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7102
7103         //First hop
7104         let mut payment_event = {
7105                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7106                 check_added_monitors!(nodes[0], 1);
7107                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7108                 assert_eq!(events.len(), 1);
7109                 SendEvent::from_event(events.remove(0))
7110         };
7111         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7112         check_added_monitors!(nodes[1], 0);
7113         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7114         expect_pending_htlcs_forwardable!(nodes[1]);
7115         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7116         assert_eq!(events_2.len(), 1);
7117         check_added_monitors!(nodes[1], 1);
7118         payment_event = SendEvent::from_event(events_2.remove(0));
7119         assert_eq!(payment_event.msgs.len(), 1);
7120
7121         //Second Hop
7122         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7123         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7124         check_added_monitors!(nodes[2], 0);
7125         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7126
7127         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7128         assert_eq!(events_3.len(), 1);
7129         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7130                 match events_3[0] {
7131                         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 } } => {
7132                                 assert!(update_add_htlcs.is_empty());
7133                                 assert!(update_fulfill_htlcs.is_empty());
7134                                 assert!(update_fail_htlcs.is_empty());
7135                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7136                                 assert!(update_fee.is_none());
7137                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7138                         },
7139                         _ => panic!("Unexpected event"),
7140                 }
7141         };
7142
7143         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7144
7145         check_added_monitors!(nodes[1], 0);
7146         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7147         expect_pending_htlcs_forwardable!(nodes[1]);
7148         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7149         assert_eq!(events_4.len(), 1);
7150
7151         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7152         match events_4[0] {
7153                 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, .. } } => {
7154                         assert!(update_add_htlcs.is_empty());
7155                         assert!(update_fulfill_htlcs.is_empty());
7156                         assert_eq!(update_fail_htlcs.len(), 1);
7157                         assert!(update_fail_malformed_htlcs.is_empty());
7158                         assert!(update_fee.is_none());
7159                 },
7160                 _ => panic!("Unexpected event"),
7161         };
7162
7163         check_added_monitors!(nodes[1], 1);
7164 }
7165
7166 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7167         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7168         // 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
7169         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7170
7171         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7172         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7173         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7174         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7175         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7176         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7177
7178         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7179
7180         // We route 2 dust-HTLCs between A and B
7181         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7182         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7183         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7184
7185         // Cache one local commitment tx as previous
7186         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7187
7188         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7189         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7190         check_added_monitors!(nodes[1], 0);
7191         expect_pending_htlcs_forwardable!(nodes[1]);
7192         check_added_monitors!(nodes[1], 1);
7193
7194         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7195         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7196         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7197         check_added_monitors!(nodes[0], 1);
7198
7199         // Cache one local commitment tx as lastest
7200         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7201
7202         let events = nodes[0].node.get_and_clear_pending_msg_events();
7203         match events[0] {
7204                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7205                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7206                 },
7207                 _ => panic!("Unexpected event"),
7208         }
7209         match events[1] {
7210                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7211                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7212                 },
7213                 _ => panic!("Unexpected event"),
7214         }
7215
7216         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7217         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7218         if announce_latest {
7219                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7220         } else {
7221                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7222         }
7223
7224         check_closed_broadcast!(nodes[0], true);
7225         check_added_monitors!(nodes[0], 1);
7226         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7227
7228         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7229         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7230         let events = nodes[0].node.get_and_clear_pending_events();
7231         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7232         assert_eq!(events.len(), 2);
7233         let mut first_failed = false;
7234         for event in events {
7235                 match event {
7236                         Event::PaymentPathFailed { payment_hash, .. } => {
7237                                 if payment_hash == payment_hash_1 {
7238                                         assert!(!first_failed);
7239                                         first_failed = true;
7240                                 } else {
7241                                         assert_eq!(payment_hash, payment_hash_2);
7242                                 }
7243                         }
7244                         _ => panic!("Unexpected event"),
7245                 }
7246         }
7247 }
7248
7249 #[test]
7250 fn test_failure_delay_dust_htlc_local_commitment() {
7251         do_test_failure_delay_dust_htlc_local_commitment(true);
7252         do_test_failure_delay_dust_htlc_local_commitment(false);
7253 }
7254
7255 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7256         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7257         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7258         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7259         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7260         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7261         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7262
7263         let chanmon_cfgs = create_chanmon_cfgs(3);
7264         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7265         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7266         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7267         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7268
7269         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7270
7271         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7272         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7273
7274         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7275         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7276
7277         // We revoked bs_commitment_tx
7278         if revoked {
7279                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7280                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7281         }
7282
7283         let mut timeout_tx = Vec::new();
7284         if local {
7285                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7286                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7287                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7288                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7289                 expect_payment_failed!(nodes[0], dust_hash, true);
7290
7291                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7292                 check_closed_broadcast!(nodes[0], true);
7293                 check_added_monitors!(nodes[0], 1);
7294                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7295                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7296                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7297                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7298                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7299                 mine_transaction(&nodes[0], &timeout_tx[0]);
7300                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7301                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7302         } else {
7303                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7304                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7305                 check_closed_broadcast!(nodes[0], true);
7306                 check_added_monitors!(nodes[0], 1);
7307                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7308                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7309
7310                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7311                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7312                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7313                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7314                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7315                 // dust HTLC should have been failed.
7316                 expect_payment_failed!(nodes[0], dust_hash, true);
7317
7318                 if !revoked {
7319                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7320                 } else {
7321                         assert_eq!(timeout_tx[0].lock_time, 0);
7322                 }
7323                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7324                 mine_transaction(&nodes[0], &timeout_tx[0]);
7325                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7326                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7327                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7328         }
7329 }
7330
7331 #[test]
7332 fn test_sweep_outbound_htlc_failure_update() {
7333         do_test_sweep_outbound_htlc_failure_update(false, true);
7334         do_test_sweep_outbound_htlc_failure_update(false, false);
7335         do_test_sweep_outbound_htlc_failure_update(true, false);
7336 }
7337
7338 #[test]
7339 fn test_user_configurable_csv_delay() {
7340         // We test our channel constructors yield errors when we pass them absurd csv delay
7341
7342         let mut low_our_to_self_config = UserConfig::default();
7343         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7344         let mut high_their_to_self_config = UserConfig::default();
7345         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7346         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7347         let chanmon_cfgs = create_chanmon_cfgs(2);
7348         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7349         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7350         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7351
7352         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7353         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7354                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7355                 &low_our_to_self_config, 0, 42)
7356         {
7357                 match error {
7358                         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())); },
7359                         _ => panic!("Unexpected event"),
7360                 }
7361         } else { assert!(false) }
7362
7363         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7364         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7365         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7366         open_channel.to_self_delay = 200;
7367         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7368                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7369                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7370         {
7371                 match error {
7372                         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()));  },
7373                         _ => panic!("Unexpected event"),
7374                 }
7375         } else { assert!(false); }
7376
7377         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7378         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7379         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()));
7380         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7381         accept_channel.to_self_delay = 200;
7382         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7383         let reason_msg;
7384         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7385                 match action {
7386                         &ErrorAction::SendErrorMessage { ref msg } => {
7387                                 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()));
7388                                 reason_msg = msg.data.clone();
7389                         },
7390                         _ => { panic!(); }
7391                 }
7392         } else { panic!(); }
7393         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7394
7395         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7396         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7397         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7398         open_channel.to_self_delay = 200;
7399         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7400                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7401                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7402         {
7403                 match error {
7404                         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())); },
7405                         _ => panic!("Unexpected event"),
7406                 }
7407         } else { assert!(false); }
7408 }
7409
7410 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7411         // When we get a data_loss_protect proving we're behind, we immediately panic as the
7412         // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7413         // panic message informs the user they should force-close without broadcasting, which is tested
7414         // if `reconnect_panicing` is not set.
7415         let persister;
7416         let logger;
7417         let fee_estimator;
7418         let tx_broadcaster;
7419         let chain_source;
7420         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7421         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7422         // during signing due to revoked tx
7423         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7424         let keys_manager = &chanmon_cfgs[0].keys_manager;
7425         let monitor;
7426         let node_state_0;
7427         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7428         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7429         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7430
7431         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7432
7433         // Cache node A state before any channel update
7434         let previous_node_state = nodes[0].node.encode();
7435         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7436         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7437
7438         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7439         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7440
7441         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7442         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7443
7444         // Restore node A from previous state
7445         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7446         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7447         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7448         tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7449         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7450         persister = test_utils::TestPersister::new();
7451         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7452         node_state_0 = {
7453                 let mut channel_monitors = HashMap::new();
7454                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7455                 <(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 {
7456                         keys_manager: keys_manager,
7457                         fee_estimator: &fee_estimator,
7458                         chain_monitor: &monitor,
7459                         logger: &logger,
7460                         tx_broadcaster: &tx_broadcaster,
7461                         default_config: UserConfig::default(),
7462                         channel_monitors,
7463                 }).unwrap().1
7464         };
7465         nodes[0].node = &node_state_0;
7466         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7467         nodes[0].chain_monitor = &monitor;
7468         nodes[0].chain_source = &chain_source;
7469
7470         check_added_monitors!(nodes[0], 1);
7471
7472         if reconnect_panicing {
7473                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7474                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7475
7476                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7477
7478                 // Check we close channel detecting A is fallen-behind
7479                 // Check that we sent the warning message when we detected that A has fallen behind,
7480                 // and give the possibility for A to recover from the warning.
7481                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7482                 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7483                 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7484
7485                 {
7486                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7487                         // The node B should not broadcast the transaction to force close the channel!
7488                         assert!(node_txn.is_empty());
7489                 }
7490
7491                 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7492                 // Check A panics upon seeing proof it has fallen behind.
7493                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7494                 return; // By this point we should have panic'ed!
7495         }
7496
7497         nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7498         check_added_monitors!(nodes[0], 1);
7499         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7500         {
7501                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7502                 assert_eq!(node_txn.len(), 0);
7503         }
7504
7505         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7506                 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7507                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7508                         match action {
7509                                 &ErrorAction::SendErrorMessage { ref msg } => {
7510                                         assert_eq!(msg.data, "Channel force-closed");
7511                                 },
7512                                 _ => panic!("Unexpected event!"),
7513                         }
7514                 } else {
7515                         panic!("Unexpected event {:?}", msg)
7516                 }
7517         }
7518
7519         // after the warning message sent by B, we should not able to
7520         // use the channel, or reconnect with success to the channel.
7521         assert!(nodes[0].node.list_usable_channels().is_empty());
7522         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7523         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7524         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7525
7526         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7527         let mut err_msgs_0 = Vec::with_capacity(1);
7528         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7529                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7530                         match action {
7531                                 &ErrorAction::SendErrorMessage { ref msg } => {
7532                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7533                                         err_msgs_0.push(msg.clone());
7534                                 },
7535                                 _ => panic!("Unexpected event!"),
7536                         }
7537                 } else {
7538                         panic!("Unexpected event!");
7539                 }
7540         }
7541         assert_eq!(err_msgs_0.len(), 1);
7542         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7543         assert!(nodes[1].node.list_usable_channels().is_empty());
7544         check_added_monitors!(nodes[1], 1);
7545         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7546         check_closed_broadcast!(nodes[1], false);
7547 }
7548
7549 #[test]
7550 #[should_panic]
7551 fn test_data_loss_protect_showing_stale_state_panics() {
7552         do_test_data_loss_protect(true);
7553 }
7554
7555 #[test]
7556 fn test_force_close_without_broadcast() {
7557         do_test_data_loss_protect(false);
7558 }
7559
7560 #[test]
7561 fn test_check_htlc_underpaying() {
7562         // Send payment through A -> B but A is maliciously
7563         // sending a probe payment (i.e less than expected value0
7564         // to B, B should refuse payment.
7565
7566         let chanmon_cfgs = create_chanmon_cfgs(2);
7567         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7568         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7569         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7570
7571         // Create some initial channels
7572         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7573
7574         let scorer = test_utils::TestScorer::with_penalty(0);
7575         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7576         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7577         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();
7578         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7579         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7580         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7581         check_added_monitors!(nodes[0], 1);
7582
7583         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7584         assert_eq!(events.len(), 1);
7585         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7586         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7587         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7588
7589         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7590         // and then will wait a second random delay before failing the HTLC back:
7591         expect_pending_htlcs_forwardable!(nodes[1]);
7592         expect_pending_htlcs_forwardable!(nodes[1]);
7593
7594         // Node 3 is expecting payment of 100_000 but received 10_000,
7595         // it should fail htlc like we didn't know the preimage.
7596         nodes[1].node.process_pending_htlc_forwards();
7597
7598         let events = nodes[1].node.get_and_clear_pending_msg_events();
7599         assert_eq!(events.len(), 1);
7600         let (update_fail_htlc, commitment_signed) = match events[0] {
7601                 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 } } => {
7602                         assert!(update_add_htlcs.is_empty());
7603                         assert!(update_fulfill_htlcs.is_empty());
7604                         assert_eq!(update_fail_htlcs.len(), 1);
7605                         assert!(update_fail_malformed_htlcs.is_empty());
7606                         assert!(update_fee.is_none());
7607                         (update_fail_htlcs[0].clone(), commitment_signed)
7608                 },
7609                 _ => panic!("Unexpected event"),
7610         };
7611         check_added_monitors!(nodes[1], 1);
7612
7613         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7614         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7615
7616         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7617         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7618         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7619         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7620 }
7621
7622 #[test]
7623 fn test_announce_disable_channels() {
7624         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7625         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7626
7627         let chanmon_cfgs = create_chanmon_cfgs(2);
7628         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7629         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7630         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7631
7632         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7633         create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7634         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7635
7636         // Disconnect peers
7637         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7638         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7639
7640         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7641         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7642         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7643         assert_eq!(msg_events.len(), 3);
7644         let mut chans_disabled = HashMap::new();
7645         for e in msg_events {
7646                 match e {
7647                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7648                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7649                                 // Check that each channel gets updated exactly once
7650                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7651                                         panic!("Generated ChannelUpdate for wrong chan!");
7652                                 }
7653                         },
7654                         _ => panic!("Unexpected event"),
7655                 }
7656         }
7657         // Reconnect peers
7658         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7659         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7660         assert_eq!(reestablish_1.len(), 3);
7661         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7662         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7663         assert_eq!(reestablish_2.len(), 3);
7664
7665         // Reestablish chan_1
7666         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7667         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7668         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7669         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7670         // Reestablish chan_2
7671         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7672         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7673         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7674         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7675         // Reestablish chan_3
7676         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7677         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7678         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7679         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7680
7681         nodes[0].node.timer_tick_occurred();
7682         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7683         nodes[0].node.timer_tick_occurred();
7684         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7685         assert_eq!(msg_events.len(), 3);
7686         for e in msg_events {
7687                 match e {
7688                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7689                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7690                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7691                                         // Each update should have a higher timestamp than the previous one, replacing
7692                                         // the old one.
7693                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7694                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7695                                 }
7696                         },
7697                         _ => panic!("Unexpected event"),
7698                 }
7699         }
7700         // Check that each channel gets updated exactly once
7701         assert!(chans_disabled.is_empty());
7702 }
7703
7704 #[test]
7705 fn test_bump_penalty_txn_on_revoked_commitment() {
7706         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7707         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7708
7709         let chanmon_cfgs = create_chanmon_cfgs(2);
7710         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7711         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7712         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7713
7714         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7715
7716         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7717         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7718                 .with_features(InvoiceFeatures::known());
7719         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7720         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7721
7722         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7723         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7724         assert_eq!(revoked_txn[0].output.len(), 4);
7725         assert_eq!(revoked_txn[0].input.len(), 1);
7726         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7727         let revoked_txid = revoked_txn[0].txid();
7728
7729         let mut penalty_sum = 0;
7730         for outp in revoked_txn[0].output.iter() {
7731                 if outp.script_pubkey.is_v0_p2wsh() {
7732                         penalty_sum += outp.value;
7733                 }
7734         }
7735
7736         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7737         let header_114 = connect_blocks(&nodes[1], 14);
7738
7739         // Actually revoke tx by claiming a HTLC
7740         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7741         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7742         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7743         check_added_monitors!(nodes[1], 1);
7744
7745         // One or more justice tx should have been broadcast, check it
7746         let penalty_1;
7747         let feerate_1;
7748         {
7749                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7750                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7751                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7752                 assert_eq!(node_txn[0].output.len(), 1);
7753                 check_spends!(node_txn[0], revoked_txn[0]);
7754                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7755                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7756                 penalty_1 = node_txn[0].txid();
7757                 node_txn.clear();
7758         };
7759
7760         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7761         connect_blocks(&nodes[1], 15);
7762         let mut penalty_2 = penalty_1;
7763         let mut feerate_2 = 0;
7764         {
7765                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7766                 assert_eq!(node_txn.len(), 1);
7767                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7768                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7769                         assert_eq!(node_txn[0].output.len(), 1);
7770                         check_spends!(node_txn[0], revoked_txn[0]);
7771                         penalty_2 = node_txn[0].txid();
7772                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7773                         assert_ne!(penalty_2, penalty_1);
7774                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7775                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7776                         // Verify 25% bump heuristic
7777                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7778                         node_txn.clear();
7779                 }
7780         }
7781         assert_ne!(feerate_2, 0);
7782
7783         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7784         connect_blocks(&nodes[1], 1);
7785         let penalty_3;
7786         let mut feerate_3 = 0;
7787         {
7788                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7789                 assert_eq!(node_txn.len(), 1);
7790                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7791                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7792                         assert_eq!(node_txn[0].output.len(), 1);
7793                         check_spends!(node_txn[0], revoked_txn[0]);
7794                         penalty_3 = node_txn[0].txid();
7795                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7796                         assert_ne!(penalty_3, penalty_2);
7797                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7798                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7799                         // Verify 25% bump heuristic
7800                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7801                         node_txn.clear();
7802                 }
7803         }
7804         assert_ne!(feerate_3, 0);
7805
7806         nodes[1].node.get_and_clear_pending_events();
7807         nodes[1].node.get_and_clear_pending_msg_events();
7808 }
7809
7810 #[test]
7811 fn test_bump_penalty_txn_on_revoked_htlcs() {
7812         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7813         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7814
7815         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7816         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7817         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7818         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7819         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7820
7821         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7822         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7823         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7824         let scorer = test_utils::TestScorer::with_penalty(0);
7825         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7826         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7827                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7828         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7829         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7830         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7831                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7832         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7833
7834         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7835         assert_eq!(revoked_local_txn[0].input.len(), 1);
7836         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7837
7838         // Revoke local commitment tx
7839         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7840
7841         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7842         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7843         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7844         check_closed_broadcast!(nodes[1], true);
7845         check_added_monitors!(nodes[1], 1);
7846         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7847         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7848
7849         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7850         assert_eq!(revoked_htlc_txn.len(), 3);
7851         check_spends!(revoked_htlc_txn[1], chan.3);
7852
7853         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7854         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7855         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7856
7857         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7858         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7859         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7860         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7861
7862         // Broadcast set of revoked txn on A
7863         let hash_128 = connect_blocks(&nodes[0], 40);
7864         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7865         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7866         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7867         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7868         let events = nodes[0].node.get_and_clear_pending_events();
7869         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7870         match events[1] {
7871                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7872                 _ => panic!("Unexpected event"),
7873         }
7874         let first;
7875         let feerate_1;
7876         let penalty_txn;
7877         {
7878                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7879                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7880                 // Verify claim tx are spending revoked HTLC txn
7881
7882                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7883                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7884                 // which are included in the same block (they are broadcasted because we scan the
7885                 // transactions linearly and generate claims as we go, they likely should be removed in the
7886                 // future).
7887                 assert_eq!(node_txn[0].input.len(), 1);
7888                 check_spends!(node_txn[0], revoked_local_txn[0]);
7889                 assert_eq!(node_txn[1].input.len(), 1);
7890                 check_spends!(node_txn[1], revoked_local_txn[0]);
7891                 assert_eq!(node_txn[2].input.len(), 1);
7892                 check_spends!(node_txn[2], revoked_local_txn[0]);
7893
7894                 // Each of the three justice transactions claim a separate (single) output of the three
7895                 // available, which we check here:
7896                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7897                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7898                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7899
7900                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7901                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7902
7903                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7904                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7905                 // a remote commitment tx has already been confirmed).
7906                 check_spends!(node_txn[3], chan.3);
7907
7908                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7909                 // output, checked above).
7910                 assert_eq!(node_txn[4].input.len(), 2);
7911                 assert_eq!(node_txn[4].output.len(), 1);
7912                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7913
7914                 first = node_txn[4].txid();
7915                 // Store both feerates for later comparison
7916                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7917                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7918                 penalty_txn = vec![node_txn[2].clone()];
7919                 node_txn.clear();
7920         }
7921
7922         // Connect one more block to see if bumped penalty are issued for HTLC txn
7923         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7924         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7925         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7926         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7927         {
7928                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7929                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7930
7931                 check_spends!(node_txn[0], revoked_local_txn[0]);
7932                 check_spends!(node_txn[1], revoked_local_txn[0]);
7933                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7934                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7935                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7936                 } else {
7937                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7938                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7939                 }
7940
7941                 node_txn.clear();
7942         };
7943
7944         // Few more blocks to confirm penalty txn
7945         connect_blocks(&nodes[0], 4);
7946         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7947         let header_144 = connect_blocks(&nodes[0], 9);
7948         let node_txn = {
7949                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7950                 assert_eq!(node_txn.len(), 1);
7951
7952                 assert_eq!(node_txn[0].input.len(), 2);
7953                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7954                 // Verify bumped tx is different and 25% bump heuristic
7955                 assert_ne!(first, node_txn[0].txid());
7956                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7957                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7958                 assert!(feerate_2 * 100 > feerate_1 * 125);
7959                 let txn = vec![node_txn[0].clone()];
7960                 node_txn.clear();
7961                 txn
7962         };
7963         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7964         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7965         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7966         connect_blocks(&nodes[0], 20);
7967         {
7968                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7969                 // We verify than no new transaction has been broadcast because previously
7970                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7971                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7972                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7973                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7974                 // up bumped justice generation.
7975                 assert_eq!(node_txn.len(), 0);
7976                 node_txn.clear();
7977         }
7978         check_closed_broadcast!(nodes[0], true);
7979         check_added_monitors!(nodes[0], 1);
7980 }
7981
7982 #[test]
7983 fn test_bump_penalty_txn_on_remote_commitment() {
7984         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7985         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7986
7987         // Create 2 HTLCs
7988         // Provide preimage for one
7989         // Check aggregation
7990
7991         let chanmon_cfgs = create_chanmon_cfgs(2);
7992         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7993         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7994         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7995
7996         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7997         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7998         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7999
8000         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8001         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8002         assert_eq!(remote_txn[0].output.len(), 4);
8003         assert_eq!(remote_txn[0].input.len(), 1);
8004         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8005
8006         // Claim a HTLC without revocation (provide B monitor with preimage)
8007         nodes[1].node.claim_funds(payment_preimage);
8008         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
8009         mine_transaction(&nodes[1], &remote_txn[0]);
8010         check_added_monitors!(nodes[1], 2);
8011         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8012
8013         // One or more claim tx should have been broadcast, check it
8014         let timeout;
8015         let preimage;
8016         let preimage_bump;
8017         let feerate_timeout;
8018         let feerate_preimage;
8019         {
8020                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8021                 // 9 transactions including:
8022                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8023                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8024                 // 2 * HTLC-Success (one RBF bump we'll check later)
8025                 // 1 * HTLC-Timeout
8026                 assert_eq!(node_txn.len(), 8);
8027                 assert_eq!(node_txn[0].input.len(), 1);
8028                 assert_eq!(node_txn[6].input.len(), 1);
8029                 check_spends!(node_txn[0], remote_txn[0]);
8030                 check_spends!(node_txn[6], remote_txn[0]);
8031
8032                 check_spends!(node_txn[1], chan.3);
8033                 check_spends!(node_txn[2], node_txn[1]);
8034
8035                 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
8036                         preimage_bump = node_txn[3].clone();
8037                         check_spends!(node_txn[3], remote_txn[0]);
8038
8039                         assert_eq!(node_txn[1], node_txn[4]);
8040                         assert_eq!(node_txn[2], node_txn[5]);
8041                 } else {
8042                         preimage_bump = node_txn[7].clone();
8043                         check_spends!(node_txn[7], remote_txn[0]);
8044                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8045
8046                         assert_eq!(node_txn[1], node_txn[3]);
8047                         assert_eq!(node_txn[2], node_txn[4]);
8048                 }
8049
8050                 timeout = node_txn[6].txid();
8051                 let index = node_txn[6].input[0].previous_output.vout;
8052                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8053                 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8054
8055                 preimage = node_txn[0].txid();
8056                 let index = node_txn[0].input[0].previous_output.vout;
8057                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8058                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8059
8060                 node_txn.clear();
8061         };
8062         assert_ne!(feerate_timeout, 0);
8063         assert_ne!(feerate_preimage, 0);
8064
8065         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8066         connect_blocks(&nodes[1], 15);
8067         {
8068                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8069                 assert_eq!(node_txn.len(), 1);
8070                 assert_eq!(node_txn[0].input.len(), 1);
8071                 assert_eq!(preimage_bump.input.len(), 1);
8072                 check_spends!(node_txn[0], remote_txn[0]);
8073                 check_spends!(preimage_bump, remote_txn[0]);
8074
8075                 let index = preimage_bump.input[0].previous_output.vout;
8076                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8077                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8078                 assert!(new_feerate * 100 > feerate_timeout * 125);
8079                 assert_ne!(timeout, preimage_bump.txid());
8080
8081                 let index = node_txn[0].input[0].previous_output.vout;
8082                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8083                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8084                 assert!(new_feerate * 100 > feerate_preimage * 125);
8085                 assert_ne!(preimage, node_txn[0].txid());
8086
8087                 node_txn.clear();
8088         }
8089
8090         nodes[1].node.get_and_clear_pending_events();
8091         nodes[1].node.get_and_clear_pending_msg_events();
8092 }
8093
8094 #[test]
8095 fn test_counterparty_raa_skip_no_crash() {
8096         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8097         // commitment transaction, we would have happily carried on and provided them the next
8098         // commitment transaction based on one RAA forward. This would probably eventually have led to
8099         // channel closure, but it would not have resulted in funds loss. Still, our
8100         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8101         // check simply that the channel is closed in response to such an RAA, but don't check whether
8102         // we decide to punish our counterparty for revoking their funds (as we don't currently
8103         // implement that).
8104         let chanmon_cfgs = create_chanmon_cfgs(2);
8105         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8106         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8107         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8108         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8109
8110         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8111         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8112
8113         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8114
8115         // Make signer believe we got a counterparty signature, so that it allows the revocation
8116         keys.get_enforcement_state().last_holder_commitment -= 1;
8117         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8118
8119         // Must revoke without gaps
8120         keys.get_enforcement_state().last_holder_commitment -= 1;
8121         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8122
8123         keys.get_enforcement_state().last_holder_commitment -= 1;
8124         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8125                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8126
8127         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8128                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8129         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8130         check_added_monitors!(nodes[1], 1);
8131         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8132 }
8133
8134 #[test]
8135 fn test_bump_txn_sanitize_tracking_maps() {
8136         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8137         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8138
8139         let chanmon_cfgs = create_chanmon_cfgs(2);
8140         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8141         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8142         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8143
8144         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8145         // Lock HTLC in both directions
8146         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8147         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8148
8149         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8150         assert_eq!(revoked_local_txn[0].input.len(), 1);
8151         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8152
8153         // Revoke local commitment tx
8154         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8155
8156         // Broadcast set of revoked txn on A
8157         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8158         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8159         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8160
8161         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8162         check_closed_broadcast!(nodes[0], true);
8163         check_added_monitors!(nodes[0], 1);
8164         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8165         let penalty_txn = {
8166                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8167                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8168                 check_spends!(node_txn[0], revoked_local_txn[0]);
8169                 check_spends!(node_txn[1], revoked_local_txn[0]);
8170                 check_spends!(node_txn[2], revoked_local_txn[0]);
8171                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8172                 node_txn.clear();
8173                 penalty_txn
8174         };
8175         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8176         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8177         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8178         {
8179                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8180                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8181                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8182         }
8183 }
8184
8185 #[test]
8186 fn test_pending_claimed_htlc_no_balance_underflow() {
8187         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8188         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8189         let chanmon_cfgs = create_chanmon_cfgs(2);
8190         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8191         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8192         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8193         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8194
8195         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8196         nodes[1].node.claim_funds(payment_preimage);
8197         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8198         check_added_monitors!(nodes[1], 1);
8199         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8200
8201         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8202         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8203         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8204         check_added_monitors!(nodes[0], 1);
8205         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8206
8207         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8208         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8209         // can get our balance.
8210
8211         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8212         // the public key of the only hop. This works around ChannelDetails not showing the
8213         // almost-claimed HTLC as available balance.
8214         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8215         route.payment_params = None; // This is all wrong, but unnecessary
8216         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8217         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8218         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8219
8220         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8221 }
8222
8223 #[test]
8224 fn test_channel_conf_timeout() {
8225         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8226         // confirm within 2016 blocks, as recommended by BOLT 2.
8227         let chanmon_cfgs = create_chanmon_cfgs(2);
8228         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8229         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8230         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8231
8232         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8233
8234         // The outbound node should wait forever for confirmation:
8235         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8236         // copied here instead of directly referencing the constant.
8237         connect_blocks(&nodes[0], 2016);
8238         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8239
8240         // The inbound node should fail the channel after exactly 2016 blocks
8241         connect_blocks(&nodes[1], 2015);
8242         check_added_monitors!(nodes[1], 0);
8243         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8244
8245         connect_blocks(&nodes[1], 1);
8246         check_added_monitors!(nodes[1], 1);
8247         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8248         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8249         assert_eq!(close_ev.len(), 1);
8250         match close_ev[0] {
8251                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8252                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8253                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8254                 },
8255                 _ => panic!("Unexpected event"),
8256         }
8257 }
8258
8259 #[test]
8260 fn test_override_channel_config() {
8261         let chanmon_cfgs = create_chanmon_cfgs(2);
8262         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8263         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8264         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8265
8266         // Node0 initiates a channel to node1 using the override config.
8267         let mut override_config = UserConfig::default();
8268         override_config.channel_handshake_config.our_to_self_delay = 200;
8269
8270         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8271
8272         // Assert the channel created by node0 is using the override config.
8273         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8274         assert_eq!(res.channel_flags, 0);
8275         assert_eq!(res.to_self_delay, 200);
8276 }
8277
8278 #[test]
8279 fn test_override_0msat_htlc_minimum() {
8280         let mut zero_config = UserConfig::default();
8281         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8282         let chanmon_cfgs = create_chanmon_cfgs(2);
8283         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8284         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8285         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8286
8287         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8288         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8289         assert_eq!(res.htlc_minimum_msat, 1);
8290
8291         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8292         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8293         assert_eq!(res.htlc_minimum_msat, 1);
8294 }
8295
8296 #[test]
8297 fn test_channel_update_has_correct_htlc_maximum_msat() {
8298         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8299         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8300         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8301         // 90% of the `channel_value`.
8302         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8303
8304         let mut config_30_percent = UserConfig::default();
8305         config_30_percent.channel_handshake_config.announced_channel = true;
8306         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8307         let mut config_50_percent = UserConfig::default();
8308         config_50_percent.channel_handshake_config.announced_channel = true;
8309         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8310         let mut config_95_percent = UserConfig::default();
8311         config_95_percent.channel_handshake_config.announced_channel = true;
8312         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8313         let mut config_100_percent = UserConfig::default();
8314         config_100_percent.channel_handshake_config.announced_channel = true;
8315         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8316
8317         let chanmon_cfgs = create_chanmon_cfgs(4);
8318         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8319         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[Some(config_30_percent), Some(config_50_percent), Some(config_95_percent), Some(config_100_percent)]);
8320         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8321
8322         let channel_value_satoshis = 100000;
8323         let channel_value_msat = channel_value_satoshis * 1000;
8324         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8325         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8326         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8327
8328         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001, InitFeatures::known(), InitFeatures::known());
8329         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001, InitFeatures::known(), InitFeatures::known());
8330
8331         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8332         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8333         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8334         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8335         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8336         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8337
8338         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8339         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8340         // `channel_value`.
8341         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8342         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8343         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8344         // `channel_value`.
8345         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8346 }
8347
8348 #[test]
8349 fn test_manually_accept_inbound_channel_request() {
8350         let mut manually_accept_conf = UserConfig::default();
8351         manually_accept_conf.manually_accept_inbound_channels = true;
8352         let chanmon_cfgs = create_chanmon_cfgs(2);
8353         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8354         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8355         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8356
8357         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8358         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8359
8360         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8361
8362         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8363         // accepting the inbound channel request.
8364         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8365
8366         let events = nodes[1].node.get_and_clear_pending_events();
8367         match events[0] {
8368                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8369                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8370                 }
8371                 _ => panic!("Unexpected event"),
8372         }
8373
8374         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8375         assert_eq!(accept_msg_ev.len(), 1);
8376
8377         match accept_msg_ev[0] {
8378                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8379                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8380                 }
8381                 _ => panic!("Unexpected event"),
8382         }
8383
8384         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8385
8386         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8387         assert_eq!(close_msg_ev.len(), 1);
8388
8389         let events = nodes[1].node.get_and_clear_pending_events();
8390         match events[0] {
8391                 Event::ChannelClosed { user_channel_id, .. } => {
8392                         assert_eq!(user_channel_id, 23);
8393                 }
8394                 _ => panic!("Unexpected event"),
8395         }
8396 }
8397
8398 #[test]
8399 fn test_manually_reject_inbound_channel_request() {
8400         let mut manually_accept_conf = UserConfig::default();
8401         manually_accept_conf.manually_accept_inbound_channels = true;
8402         let chanmon_cfgs = create_chanmon_cfgs(2);
8403         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8404         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8405         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8406
8407         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8408         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8409
8410         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8411
8412         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8413         // rejecting the inbound channel request.
8414         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8415
8416         let events = nodes[1].node.get_and_clear_pending_events();
8417         match events[0] {
8418                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8419                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8420                 }
8421                 _ => panic!("Unexpected event"),
8422         }
8423
8424         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8425         assert_eq!(close_msg_ev.len(), 1);
8426
8427         match close_msg_ev[0] {
8428                 MessageSendEvent::HandleError { ref node_id, .. } => {
8429                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8430                 }
8431                 _ => panic!("Unexpected event"),
8432         }
8433         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8434 }
8435
8436 #[test]
8437 fn test_reject_funding_before_inbound_channel_accepted() {
8438         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8439         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8440         // the node operator before the counterparty sends a `FundingCreated` message. If a
8441         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8442         // and the channel should be closed.
8443         let mut manually_accept_conf = UserConfig::default();
8444         manually_accept_conf.manually_accept_inbound_channels = true;
8445         let chanmon_cfgs = create_chanmon_cfgs(2);
8446         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8447         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8448         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8449
8450         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8451         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8452         let temp_channel_id = res.temporary_channel_id;
8453
8454         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8455
8456         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8457         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8458
8459         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8460         nodes[1].node.get_and_clear_pending_events();
8461
8462         // Get the `AcceptChannel` message of `nodes[1]` without calling
8463         // `ChannelManager::accept_inbound_channel`, which generates a
8464         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8465         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8466         // succeed when `nodes[0]` is passed to it.
8467         {
8468                 let mut lock;
8469                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8470                 let accept_chan_msg = channel.get_accept_channel_message();
8471                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8472         }
8473
8474         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8475
8476         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8477         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8478
8479         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8480         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8481
8482         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8483         assert_eq!(close_msg_ev.len(), 1);
8484
8485         let expected_err = "FundingCreated message received before the channel was accepted";
8486         match close_msg_ev[0] {
8487                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8488                         assert_eq!(msg.channel_id, temp_channel_id);
8489                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8490                         assert_eq!(msg.data, expected_err);
8491                 }
8492                 _ => panic!("Unexpected event"),
8493         }
8494
8495         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8496 }
8497
8498 #[test]
8499 fn test_can_not_accept_inbound_channel_twice() {
8500         let mut manually_accept_conf = UserConfig::default();
8501         manually_accept_conf.manually_accept_inbound_channels = true;
8502         let chanmon_cfgs = create_chanmon_cfgs(2);
8503         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8504         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8505         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8506
8507         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8508         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8509
8510         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8511
8512         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8513         // accepting the inbound channel request.
8514         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8515
8516         let events = nodes[1].node.get_and_clear_pending_events();
8517         match events[0] {
8518                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8519                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8520                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8521                         match api_res {
8522                                 Err(APIError::APIMisuseError { err }) => {
8523                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8524                                 },
8525                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8526                                 Err(_) => panic!("Unexpected Error"),
8527                         }
8528                 }
8529                 _ => panic!("Unexpected event"),
8530         }
8531
8532         // Ensure that the channel wasn't closed after attempting to accept it twice.
8533         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8534         assert_eq!(accept_msg_ev.len(), 1);
8535
8536         match accept_msg_ev[0] {
8537                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8538                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8539                 }
8540                 _ => panic!("Unexpected event"),
8541         }
8542 }
8543
8544 #[test]
8545 fn test_can_not_accept_unknown_inbound_channel() {
8546         let chanmon_cfg = create_chanmon_cfgs(2);
8547         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8548         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8549         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8550
8551         let unknown_channel_id = [0; 32];
8552         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8553         match api_res {
8554                 Err(APIError::ChannelUnavailable { err }) => {
8555                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8556                 },
8557                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8558                 Err(_) => panic!("Unexpected Error"),
8559         }
8560 }
8561
8562 #[test]
8563 fn test_simple_mpp() {
8564         // Simple test of sending a multi-path payment.
8565         let chanmon_cfgs = create_chanmon_cfgs(4);
8566         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8567         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8568         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8569
8570         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8571         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8572         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8573         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8574
8575         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8576         let path = route.paths[0].clone();
8577         route.paths.push(path);
8578         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8579         route.paths[0][0].short_channel_id = chan_1_id;
8580         route.paths[0][1].short_channel_id = chan_3_id;
8581         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8582         route.paths[1][0].short_channel_id = chan_2_id;
8583         route.paths[1][1].short_channel_id = chan_4_id;
8584         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8585         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8586 }
8587
8588 #[test]
8589 fn test_preimage_storage() {
8590         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8591         let chanmon_cfgs = create_chanmon_cfgs(2);
8592         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8593         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8594         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8595
8596         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8597
8598         {
8599                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8600                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8601                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8602                 check_added_monitors!(nodes[0], 1);
8603                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8604                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8605                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8606                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8607         }
8608         // Note that after leaving the above scope we have no knowledge of any arguments or return
8609         // values from previous calls.
8610         expect_pending_htlcs_forwardable!(nodes[1]);
8611         let events = nodes[1].node.get_and_clear_pending_events();
8612         assert_eq!(events.len(), 1);
8613         match events[0] {
8614                 Event::PaymentReceived { ref purpose, .. } => {
8615                         match &purpose {
8616                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8617                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8618                                 },
8619                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8620                         }
8621                 },
8622                 _ => panic!("Unexpected event"),
8623         }
8624 }
8625
8626 #[test]
8627 #[allow(deprecated)]
8628 fn test_secret_timeout() {
8629         // Simple test of payment secret storage time outs. After
8630         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8631         let chanmon_cfgs = create_chanmon_cfgs(2);
8632         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8633         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8634         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8635
8636         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8637
8638         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8639
8640         // We should fail to register the same payment hash twice, at least until we've connected a
8641         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8642         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8643                 assert_eq!(err, "Duplicate payment hash");
8644         } else { panic!(); }
8645         let mut block = {
8646                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8647                 Block {
8648                         header: BlockHeader {
8649                                 version: 0x2000000,
8650                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8651                                 merkle_root: Default::default(),
8652                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8653                         txdata: vec![],
8654                 }
8655         };
8656         connect_block(&nodes[1], &block);
8657         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8658                 assert_eq!(err, "Duplicate payment hash");
8659         } else { panic!(); }
8660
8661         // If we then connect the second block, we should be able to register the same payment hash
8662         // again (this time getting a new payment secret).
8663         block.header.prev_blockhash = block.header.block_hash();
8664         block.header.time += 1;
8665         connect_block(&nodes[1], &block);
8666         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8667         assert_ne!(payment_secret_1, our_payment_secret);
8668
8669         {
8670                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8671                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8672                 check_added_monitors!(nodes[0], 1);
8673                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8674                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8675                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8676                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8677         }
8678         // Note that after leaving the above scope we have no knowledge of any arguments or return
8679         // values from previous calls.
8680         expect_pending_htlcs_forwardable!(nodes[1]);
8681         let events = nodes[1].node.get_and_clear_pending_events();
8682         assert_eq!(events.len(), 1);
8683         match events[0] {
8684                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8685                         assert!(payment_preimage.is_none());
8686                         assert_eq!(payment_secret, our_payment_secret);
8687                         // We don't actually have the payment preimage with which to claim this payment!
8688                 },
8689                 _ => panic!("Unexpected event"),
8690         }
8691 }
8692
8693 #[test]
8694 fn test_bad_secret_hash() {
8695         // Simple test of unregistered payment hash/invalid payment secret handling
8696         let chanmon_cfgs = create_chanmon_cfgs(2);
8697         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8698         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8699         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8700
8701         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8702
8703         let random_payment_hash = PaymentHash([42; 32]);
8704         let random_payment_secret = PaymentSecret([43; 32]);
8705         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8706         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8707
8708         // All the below cases should end up being handled exactly identically, so we macro the
8709         // resulting events.
8710         macro_rules! handle_unknown_invalid_payment_data {
8711                 () => {
8712                         check_added_monitors!(nodes[0], 1);
8713                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8714                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8715                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8716                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8717
8718                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8719                         // again to process the pending backwards-failure of the HTLC
8720                         expect_pending_htlcs_forwardable!(nodes[1]);
8721                         expect_pending_htlcs_forwardable!(nodes[1]);
8722                         check_added_monitors!(nodes[1], 1);
8723
8724                         // We should fail the payment back
8725                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8726                         match events.pop().unwrap() {
8727                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8728                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8729                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8730                                 },
8731                                 _ => panic!("Unexpected event"),
8732                         }
8733                 }
8734         }
8735
8736         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8737         // Error data is the HTLC value (100,000) and current block height
8738         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8739
8740         // Send a payment with the right payment hash but the wrong payment secret
8741         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8742         handle_unknown_invalid_payment_data!();
8743         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8744
8745         // Send a payment with a random payment hash, but the right payment secret
8746         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8747         handle_unknown_invalid_payment_data!();
8748         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8749
8750         // Send a payment with a random payment hash and random payment secret
8751         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8752         handle_unknown_invalid_payment_data!();
8753         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8754 }
8755
8756 #[test]
8757 fn test_update_err_monitor_lockdown() {
8758         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8759         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8760         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8761         //
8762         // This scenario may happen in a watchtower setup, where watchtower process a block height
8763         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8764         // commitment at same time.
8765
8766         let chanmon_cfgs = create_chanmon_cfgs(2);
8767         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8768         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8769         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8770
8771         // Create some initial channel
8772         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8773         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8774
8775         // Rebalance the network to generate htlc in the two directions
8776         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8777
8778         // Route a HTLC from node 0 to node 1 (but don't settle)
8779         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8780
8781         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8782         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8783         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8784         let persister = test_utils::TestPersister::new();
8785         let watchtower = {
8786                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8787                 let mut w = test_utils::TestVecWriter(Vec::new());
8788                 monitor.write(&mut w).unwrap();
8789                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8790                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8791                 assert!(new_monitor == *monitor);
8792                 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);
8793                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8794                 watchtower
8795         };
8796         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8797         let block = Block { header, txdata: vec![] };
8798         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8799         // transaction lock time requirements here.
8800         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8801         watchtower.chain_monitor.block_connected(&block, 200);
8802
8803         // Try to update ChannelMonitor
8804         nodes[1].node.claim_funds(preimage);
8805         check_added_monitors!(nodes[1], 1);
8806         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8807
8808         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8809         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8810         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8811         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8812                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8813                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8814                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8815                 } else { assert!(false); }
8816         } else { assert!(false); };
8817         // Our local monitor is in-sync and hasn't processed yet timeout
8818         check_added_monitors!(nodes[0], 1);
8819         let events = nodes[0].node.get_and_clear_pending_events();
8820         assert_eq!(events.len(), 1);
8821 }
8822
8823 #[test]
8824 fn test_concurrent_monitor_claim() {
8825         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8826         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8827         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8828         // state N+1 confirms. Alice claims output from state N+1.
8829
8830         let chanmon_cfgs = create_chanmon_cfgs(2);
8831         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8832         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8833         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8834
8835         // Create some initial channel
8836         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8837         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8838
8839         // Rebalance the network to generate htlc in the two directions
8840         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8841
8842         // Route a HTLC from node 0 to node 1 (but don't settle)
8843         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8844
8845         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8846         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8847         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8848         let persister = test_utils::TestPersister::new();
8849         let watchtower_alice = {
8850                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8851                 let mut w = test_utils::TestVecWriter(Vec::new());
8852                 monitor.write(&mut w).unwrap();
8853                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8854                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8855                 assert!(new_monitor == *monitor);
8856                 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);
8857                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8858                 watchtower
8859         };
8860         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8861         let block = Block { header, txdata: vec![] };
8862         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8863         // transaction lock time requirements here.
8864         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (block.clone(), 0));
8865         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8866
8867         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8868         {
8869                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8870                 assert_eq!(txn.len(), 2);
8871                 txn.clear();
8872         }
8873
8874         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8875         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8876         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8877         let persister = test_utils::TestPersister::new();
8878         let watchtower_bob = {
8879                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8880                 let mut w = test_utils::TestVecWriter(Vec::new());
8881                 monitor.write(&mut w).unwrap();
8882                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8883                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8884                 assert!(new_monitor == *monitor);
8885                 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);
8886                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8887                 watchtower
8888         };
8889         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8890         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8891
8892         // Route another payment to generate another update with still previous HTLC pending
8893         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8894         {
8895                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8896         }
8897         check_added_monitors!(nodes[1], 1);
8898
8899         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8900         assert_eq!(updates.update_add_htlcs.len(), 1);
8901         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8902         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8903                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8904                         // Watchtower Alice should already have seen the block and reject the update
8905                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8906                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8907                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8908                 } else { assert!(false); }
8909         } else { assert!(false); };
8910         // Our local monitor is in-sync and hasn't processed yet timeout
8911         check_added_monitors!(nodes[0], 1);
8912
8913         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8914         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8915         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8916
8917         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8918         let bob_state_y;
8919         {
8920                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8921                 assert_eq!(txn.len(), 2);
8922                 bob_state_y = txn[0].clone();
8923                 txn.clear();
8924         };
8925
8926         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8927         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8928         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);
8929         {
8930                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8931                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8932                 // the onchain detection of the HTLC output
8933                 assert_eq!(htlc_txn.len(), 2);
8934                 check_spends!(htlc_txn[0], bob_state_y);
8935                 check_spends!(htlc_txn[1], bob_state_y);
8936         }
8937 }
8938
8939 #[test]
8940 fn test_pre_lockin_no_chan_closed_update() {
8941         // Test that if a peer closes a channel in response to a funding_created message we don't
8942         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8943         // message).
8944         //
8945         // Doing so would imply a channel monitor update before the initial channel monitor
8946         // registration, violating our API guarantees.
8947         //
8948         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8949         // then opening a second channel with the same funding output as the first (which is not
8950         // rejected because the first channel does not exist in the ChannelManager) and closing it
8951         // before receiving funding_signed.
8952         let chanmon_cfgs = create_chanmon_cfgs(2);
8953         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8954         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8955         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8956
8957         // Create an initial channel
8958         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8959         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8960         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8961         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8962         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8963
8964         // Move the first channel through the funding flow...
8965         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8966
8967         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8968         check_added_monitors!(nodes[0], 0);
8969
8970         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8971         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8972         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8973         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8974         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8975 }
8976
8977 #[test]
8978 fn test_htlc_no_detection() {
8979         // This test is a mutation to underscore the detection logic bug we had
8980         // before #653. HTLC value routed is above the remaining balance, thus
8981         // inverting HTLC and `to_remote` output. HTLC will come second and
8982         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8983         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8984         // outputs order detection for correct spending children filtring.
8985
8986         let chanmon_cfgs = create_chanmon_cfgs(2);
8987         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8988         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8989         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8990
8991         // Create some initial channels
8992         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8993
8994         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8995         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8996         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8997         assert_eq!(local_txn[0].input.len(), 1);
8998         assert_eq!(local_txn[0].output.len(), 3);
8999         check_spends!(local_txn[0], chan_1.3);
9000
9001         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9002         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9003         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
9004         // We deliberately connect the local tx twice as this should provoke a failure calling
9005         // this test before #653 fix.
9006         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);
9007         check_closed_broadcast!(nodes[0], true);
9008         check_added_monitors!(nodes[0], 1);
9009         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
9010         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9011
9012         let htlc_timeout = {
9013                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9014                 assert_eq!(node_txn[1].input.len(), 1);
9015                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9016                 check_spends!(node_txn[1], local_txn[0]);
9017                 node_txn[1].clone()
9018         };
9019
9020         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9021         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9022         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9023         expect_payment_failed!(nodes[0], our_payment_hash, true);
9024 }
9025
9026 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9027         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9028         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9029         // Carol, Alice would be the upstream node, and Carol the downstream.)
9030         //
9031         // Steps of the test:
9032         // 1) Alice sends a HTLC to Carol through Bob.
9033         // 2) Carol doesn't settle the HTLC.
9034         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9035         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9036         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9037         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9038         // 5) Carol release the preimage to Bob off-chain.
9039         // 6) Bob claims the offered output on the broadcasted commitment.
9040         let chanmon_cfgs = create_chanmon_cfgs(3);
9041         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9042         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9043         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9044
9045         // Create some initial channels
9046         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9047         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9048
9049         // Steps (1) and (2):
9050         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9051         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9052
9053         // Check that Alice's commitment transaction now contains an output for this HTLC.
9054         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9055         check_spends!(alice_txn[0], chan_ab.3);
9056         assert_eq!(alice_txn[0].output.len(), 2);
9057         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9058         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9059         assert_eq!(alice_txn.len(), 2);
9060
9061         // Steps (3) and (4):
9062         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9063         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9064         let mut force_closing_node = 0; // Alice force-closes
9065         let mut counterparty_node = 1; // Bob if Alice force-closes
9066
9067         // Bob force-closes
9068         if !broadcast_alice {
9069                 force_closing_node = 1;
9070                 counterparty_node = 0;
9071         }
9072         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9073         check_closed_broadcast!(nodes[force_closing_node], true);
9074         check_added_monitors!(nodes[force_closing_node], 1);
9075         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9076         if go_onchain_before_fulfill {
9077                 let txn_to_broadcast = match broadcast_alice {
9078                         true => alice_txn.clone(),
9079                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9080                 };
9081                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9082                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9083                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9084                 if broadcast_alice {
9085                         check_closed_broadcast!(nodes[1], true);
9086                         check_added_monitors!(nodes[1], 1);
9087                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9088                 }
9089                 assert_eq!(bob_txn.len(), 1);
9090                 check_spends!(bob_txn[0], chan_ab.3);
9091         }
9092
9093         // Step (5):
9094         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9095         // process of removing the HTLC from their commitment transactions.
9096         nodes[2].node.claim_funds(payment_preimage);
9097         check_added_monitors!(nodes[2], 1);
9098         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9099
9100         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9101         assert!(carol_updates.update_add_htlcs.is_empty());
9102         assert!(carol_updates.update_fail_htlcs.is_empty());
9103         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9104         assert!(carol_updates.update_fee.is_none());
9105         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9106
9107         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9108         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9109         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9110         if !go_onchain_before_fulfill && broadcast_alice {
9111                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9112                 assert_eq!(events.len(), 1);
9113                 match events[0] {
9114                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9115                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9116                         },
9117                         _ => panic!("Unexpected event"),
9118                 };
9119         }
9120         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9121         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9122         // Carol<->Bob's updated commitment transaction info.
9123         check_added_monitors!(nodes[1], 2);
9124
9125         let events = nodes[1].node.get_and_clear_pending_msg_events();
9126         assert_eq!(events.len(), 2);
9127         let bob_revocation = match events[0] {
9128                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9129                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9130                         (*msg).clone()
9131                 },
9132                 _ => panic!("Unexpected event"),
9133         };
9134         let bob_updates = match events[1] {
9135                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9136                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9137                         (*updates).clone()
9138                 },
9139                 _ => panic!("Unexpected event"),
9140         };
9141
9142         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9143         check_added_monitors!(nodes[2], 1);
9144         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9145         check_added_monitors!(nodes[2], 1);
9146
9147         let events = nodes[2].node.get_and_clear_pending_msg_events();
9148         assert_eq!(events.len(), 1);
9149         let carol_revocation = match events[0] {
9150                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9151                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9152                         (*msg).clone()
9153                 },
9154                 _ => panic!("Unexpected event"),
9155         };
9156         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9157         check_added_monitors!(nodes[1], 1);
9158
9159         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9160         // here's where we put said channel's commitment tx on-chain.
9161         let mut txn_to_broadcast = alice_txn.clone();
9162         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9163         if !go_onchain_before_fulfill {
9164                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9165                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9166                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9167                 if broadcast_alice {
9168                         check_closed_broadcast!(nodes[1], true);
9169                         check_added_monitors!(nodes[1], 1);
9170                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9171                 }
9172                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9173                 if broadcast_alice {
9174                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9175                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9176                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9177                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9178                         // broadcasted.
9179                         assert_eq!(bob_txn.len(), 3);
9180                         check_spends!(bob_txn[1], chan_ab.3);
9181                 } else {
9182                         assert_eq!(bob_txn.len(), 2);
9183                         check_spends!(bob_txn[0], chan_ab.3);
9184                 }
9185         }
9186
9187         // Step (6):
9188         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9189         // broadcasted commitment transaction.
9190         {
9191                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9192                 if go_onchain_before_fulfill {
9193                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9194                         assert_eq!(bob_txn.len(), 2);
9195                 }
9196                 let script_weight = match broadcast_alice {
9197                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9198                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9199                 };
9200                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9201                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9202                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9203                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9204                 if broadcast_alice && !go_onchain_before_fulfill {
9205                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9206                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9207                 } else {
9208                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9209                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9210                 }
9211         }
9212 }
9213
9214 #[test]
9215 fn test_onchain_htlc_settlement_after_close() {
9216         do_test_onchain_htlc_settlement_after_close(true, true);
9217         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9218         do_test_onchain_htlc_settlement_after_close(true, false);
9219         do_test_onchain_htlc_settlement_after_close(false, false);
9220 }
9221
9222 #[test]
9223 fn test_duplicate_chan_id() {
9224         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9225         // already open we reject it and keep the old channel.
9226         //
9227         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9228         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9229         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9230         // updating logic for the existing channel.
9231         let chanmon_cfgs = create_chanmon_cfgs(2);
9232         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9233         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9234         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9235
9236         // Create an initial channel
9237         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9238         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9239         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9240         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()));
9241
9242         // Try to create a second channel with the same temporary_channel_id as the first and check
9243         // that it is rejected.
9244         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9245         {
9246                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9247                 assert_eq!(events.len(), 1);
9248                 match events[0] {
9249                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9250                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9251                                 // first (valid) and second (invalid) channels are closed, given they both have
9252                                 // the same non-temporary channel_id. However, currently we do not, so we just
9253                                 // move forward with it.
9254                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9255                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9256                         },
9257                         _ => panic!("Unexpected event"),
9258                 }
9259         }
9260
9261         // Move the first channel through the funding flow...
9262         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9263
9264         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9265         check_added_monitors!(nodes[0], 0);
9266
9267         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9268         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9269         {
9270                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9271                 assert_eq!(added_monitors.len(), 1);
9272                 assert_eq!(added_monitors[0].0, funding_output);
9273                 added_monitors.clear();
9274         }
9275         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9276
9277         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9278         let channel_id = funding_outpoint.to_channel_id();
9279
9280         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9281         // temporary one).
9282
9283         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9284         // Technically this is allowed by the spec, but we don't support it and there's little reason
9285         // to. Still, it shouldn't cause any other issues.
9286         open_chan_msg.temporary_channel_id = channel_id;
9287         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9288         {
9289                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9290                 assert_eq!(events.len(), 1);
9291                 match events[0] {
9292                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9293                                 // Technically, at this point, nodes[1] would be justified in thinking both
9294                                 // channels are closed, but currently we do not, so we just move forward with it.
9295                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9296                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9297                         },
9298                         _ => panic!("Unexpected event"),
9299                 }
9300         }
9301
9302         // Now try to create a second channel which has a duplicate funding output.
9303         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9304         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9305         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9306         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()));
9307         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9308
9309         let funding_created = {
9310                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9311                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9312                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9313                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9314                 // channelmanager in a possibly nonsense state instead).
9315                 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9316                 let logger = test_utils::TestLogger::new();
9317                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9318         };
9319         check_added_monitors!(nodes[0], 0);
9320         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9321         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9322         // still needs to be cleared here.
9323         check_added_monitors!(nodes[1], 1);
9324
9325         // ...still, nodes[1] will reject the duplicate channel.
9326         {
9327                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9328                 assert_eq!(events.len(), 1);
9329                 match events[0] {
9330                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9331                                 // Technically, at this point, nodes[1] would be justified in thinking both
9332                                 // channels are closed, but currently we do not, so we just move forward with it.
9333                                 assert_eq!(msg.channel_id, channel_id);
9334                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9335                         },
9336                         _ => panic!("Unexpected event"),
9337                 }
9338         }
9339
9340         // finally, finish creating the original channel and send a payment over it to make sure
9341         // everything is functional.
9342         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9343         {
9344                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9345                 assert_eq!(added_monitors.len(), 1);
9346                 assert_eq!(added_monitors[0].0, funding_output);
9347                 added_monitors.clear();
9348         }
9349
9350         let events_4 = nodes[0].node.get_and_clear_pending_events();
9351         assert_eq!(events_4.len(), 0);
9352         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9353         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9354
9355         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9356         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9357         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9358         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9359 }
9360
9361 #[test]
9362 fn test_error_chans_closed() {
9363         // Test that we properly handle error messages, closing appropriate channels.
9364         //
9365         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9366         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9367         // we can test various edge cases around it to ensure we don't regress.
9368         let chanmon_cfgs = create_chanmon_cfgs(3);
9369         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9370         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9371         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9372
9373         // Create some initial channels
9374         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9375         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9376         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9377
9378         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9379         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9380         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9381
9382         // Closing a channel from a different peer has no effect
9383         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9384         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9385
9386         // Closing one channel doesn't impact others
9387         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9388         check_added_monitors!(nodes[0], 1);
9389         check_closed_broadcast!(nodes[0], false);
9390         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9391         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9392         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9393         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);
9394         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);
9395
9396         // A null channel ID should close all channels
9397         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9398         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9399         check_added_monitors!(nodes[0], 2);
9400         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9401         let events = nodes[0].node.get_and_clear_pending_msg_events();
9402         assert_eq!(events.len(), 2);
9403         match events[0] {
9404                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9405                         assert_eq!(msg.contents.flags & 2, 2);
9406                 },
9407                 _ => panic!("Unexpected event"),
9408         }
9409         match events[1] {
9410                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9411                         assert_eq!(msg.contents.flags & 2, 2);
9412                 },
9413                 _ => panic!("Unexpected event"),
9414         }
9415         // Note that at this point users of a standard PeerHandler will end up calling
9416         // peer_disconnected with no_connection_possible set to false, duplicating the
9417         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9418         // users with their own peer handling logic. We duplicate the call here, however.
9419         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9420         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9421
9422         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9423         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9424         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9425 }
9426
9427 #[test]
9428 fn test_invalid_funding_tx() {
9429         // Test that we properly handle invalid funding transactions sent to us from a peer.
9430         //
9431         // Previously, all other major lightning implementations had failed to properly sanitize
9432         // funding transactions from their counterparties, leading to a multi-implementation critical
9433         // security vulnerability (though we always sanitized properly, we've previously had
9434         // un-released crashes in the sanitization process).
9435         //
9436         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9437         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9438         // gave up on it. We test this here by generating such a transaction.
9439         let chanmon_cfgs = create_chanmon_cfgs(2);
9440         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9441         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9442         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9443
9444         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9445         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()));
9446         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()));
9447
9448         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9449
9450         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9451         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9452         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9453         // its length.
9454         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9455         assert!(chan_utils::HTLCType::scriptlen_to_htlctype(wit_program.len()).unwrap() ==
9456                 chan_utils::HTLCType::AcceptedHTLC);
9457
9458         let wit_program_script: Script = wit_program.clone().into();
9459         for output in tx.output.iter_mut() {
9460                 // Make the confirmed funding transaction have a bogus script_pubkey
9461                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9462         }
9463
9464         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9465         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()));
9466         check_added_monitors!(nodes[1], 1);
9467
9468         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()));
9469         check_added_monitors!(nodes[0], 1);
9470
9471         let events_1 = nodes[0].node.get_and_clear_pending_events();
9472         assert_eq!(events_1.len(), 0);
9473
9474         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9475         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9476         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9477
9478         let expected_err = "funding tx had wrong script/value or output index";
9479         confirm_transaction_at(&nodes[1], &tx, 1);
9480         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9481         check_added_monitors!(nodes[1], 1);
9482         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9483         assert_eq!(events_2.len(), 1);
9484         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9485                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9486                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9487                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9488                 } else { panic!(); }
9489         } else { panic!(); }
9490         assert_eq!(nodes[1].node.list_channels().len(), 0);
9491
9492         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9493         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9494         // as its not 32 bytes long.
9495         let mut spend_tx = Transaction {
9496                 version: 2i32, lock_time: 0,
9497                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9498                         previous_output: BitcoinOutPoint {
9499                                 txid: tx.txid(),
9500                                 vout: idx as u32,
9501                         },
9502                         script_sig: Script::new(),
9503                         sequence: 0xfffffffd,
9504                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9505                 }).collect(),
9506                 output: vec![TxOut {
9507                         value: 1000,
9508                         script_pubkey: Script::new(),
9509                 }]
9510         };
9511         check_spends!(spend_tx, tx);
9512         mine_transaction(&nodes[1], &spend_tx);
9513 }
9514
9515 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9516         // In the first version of the chain::Confirm interface, after a refactor was made to not
9517         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9518         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9519         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9520         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9521         // spending transaction until height N+1 (or greater). This was due to the way
9522         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9523         // spending transaction at the height the input transaction was confirmed at, not whether we
9524         // should broadcast a spending transaction at the current height.
9525         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9526         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9527         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9528         // until we learned about an additional block.
9529         //
9530         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9531         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9532         let chanmon_cfgs = create_chanmon_cfgs(3);
9533         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9534         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9535         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9536         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9537
9538         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9539         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9540         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9541         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9542         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9543
9544         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9545         check_closed_broadcast!(nodes[1], true);
9546         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9547         check_added_monitors!(nodes[1], 1);
9548         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9549         assert_eq!(node_txn.len(), 1);
9550
9551         let conf_height = nodes[1].best_block_info().1;
9552         if !test_height_before_timelock {
9553                 connect_blocks(&nodes[1], 24 * 6);
9554         }
9555         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9556                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9557         if test_height_before_timelock {
9558                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9559                 // generate any events or broadcast any transactions
9560                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9561                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9562         } else {
9563                 // We should broadcast an HTLC transaction spending our funding transaction first
9564                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9565                 assert_eq!(spending_txn.len(), 2);
9566                 assert_eq!(spending_txn[0], node_txn[0]);
9567                 check_spends!(spending_txn[1], node_txn[0]);
9568                 // We should also generate a SpendableOutputs event with the to_self output (as its
9569                 // timelock is up).
9570                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9571                 assert_eq!(descriptor_spend_txn.len(), 1);
9572
9573                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9574                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9575                 // additional block built on top of the current chain.
9576                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9577                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9578                 expect_pending_htlcs_forwardable!(nodes[1]);
9579                 check_added_monitors!(nodes[1], 1);
9580
9581                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9582                 assert!(updates.update_add_htlcs.is_empty());
9583                 assert!(updates.update_fulfill_htlcs.is_empty());
9584                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9585                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9586                 assert!(updates.update_fee.is_none());
9587                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9588                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9589                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9590         }
9591 }
9592
9593 #[test]
9594 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9595         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9596         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9597 }
9598
9599 #[test]
9600 fn test_forwardable_regen() {
9601         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9602         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9603         // HTLCs.
9604         // We test it for both payment receipt and payment forwarding.
9605
9606         let chanmon_cfgs = create_chanmon_cfgs(3);
9607         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9608         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9609         let persister: test_utils::TestPersister;
9610         let new_chain_monitor: test_utils::TestChainMonitor;
9611         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9612         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9613         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9614         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9615
9616         // First send a payment to nodes[1]
9617         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9618         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9619         check_added_monitors!(nodes[0], 1);
9620
9621         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9622         assert_eq!(events.len(), 1);
9623         let payment_event = SendEvent::from_event(events.pop().unwrap());
9624         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9625         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9626
9627         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9628
9629         // Next send a payment which is forwarded by nodes[1]
9630         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9631         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9632         check_added_monitors!(nodes[0], 1);
9633
9634         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9635         assert_eq!(events.len(), 1);
9636         let payment_event = SendEvent::from_event(events.pop().unwrap());
9637         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9638         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9639
9640         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9641         // generated
9642         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9643
9644         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9645         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9646         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9647
9648         let nodes_1_serialized = nodes[1].node.encode();
9649         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9650         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9651         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9652         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9653
9654         persister = test_utils::TestPersister::new();
9655         let keys_manager = &chanmon_cfgs[1].keys_manager;
9656         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);
9657         nodes[1].chain_monitor = &new_chain_monitor;
9658
9659         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9660         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9661                 &mut chan_0_monitor_read, keys_manager).unwrap();
9662         assert!(chan_0_monitor_read.is_empty());
9663         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9664         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9665                 &mut chan_1_monitor_read, keys_manager).unwrap();
9666         assert!(chan_1_monitor_read.is_empty());
9667
9668         let mut nodes_1_read = &nodes_1_serialized[..];
9669         let (_, nodes_1_deserialized_tmp) = {
9670                 let mut channel_monitors = HashMap::new();
9671                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9672                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9673                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9674                         default_config: UserConfig::default(),
9675                         keys_manager,
9676                         fee_estimator: node_cfgs[1].fee_estimator,
9677                         chain_monitor: nodes[1].chain_monitor,
9678                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9679                         logger: nodes[1].logger,
9680                         channel_monitors,
9681                 }).unwrap()
9682         };
9683         nodes_1_deserialized = nodes_1_deserialized_tmp;
9684         assert!(nodes_1_read.is_empty());
9685
9686         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9687         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9688         nodes[1].node = &nodes_1_deserialized;
9689         check_added_monitors!(nodes[1], 2);
9690
9691         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9692         // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9693         // the commitment state.
9694         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9695
9696         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9697
9698         expect_pending_htlcs_forwardable!(nodes[1]);
9699         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9700         check_added_monitors!(nodes[1], 1);
9701
9702         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9703         assert_eq!(events.len(), 1);
9704         let payment_event = SendEvent::from_event(events.pop().unwrap());
9705         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9706         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9707         expect_pending_htlcs_forwardable!(nodes[2]);
9708         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9709
9710         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9711         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9712 }
9713
9714 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9715         let chanmon_cfgs = create_chanmon_cfgs(2);
9716         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9717         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9718         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9719
9720         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9721
9722         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9723                 .with_features(InvoiceFeatures::known());
9724         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9725
9726         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9727
9728         {
9729                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9730                 check_added_monitors!(nodes[0], 1);
9731                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9732                 assert_eq!(events.len(), 1);
9733                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9734                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9735                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9736         }
9737         expect_pending_htlcs_forwardable!(nodes[1]);
9738         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9739
9740         {
9741                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9742                 check_added_monitors!(nodes[0], 1);
9743                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9744                 assert_eq!(events.len(), 1);
9745                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9746                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9747                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9748                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9749                 // assume the second is a privacy attack (no longer particularly relevant
9750                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9751                 // the first HTLC delivered above.
9752         }
9753
9754         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9755         nodes[1].node.process_pending_htlc_forwards();
9756
9757         if test_for_second_fail_panic {
9758                 // Now we go fail back the first HTLC from the user end.
9759                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9760
9761                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9762                 nodes[1].node.process_pending_htlc_forwards();
9763
9764                 check_added_monitors!(nodes[1], 1);
9765                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9766                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9767
9768                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9769                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9770                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9771
9772                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9773                 assert_eq!(failure_events.len(), 2);
9774                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9775                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9776         } else {
9777                 // Let the second HTLC fail and claim the first
9778                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9779                 nodes[1].node.process_pending_htlc_forwards();
9780
9781                 check_added_monitors!(nodes[1], 1);
9782                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9783                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9784                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9785
9786                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9787
9788                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9789         }
9790 }
9791
9792 #[test]
9793 fn test_dup_htlc_second_fail_panic() {
9794         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9795         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9796         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9797         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9798         do_test_dup_htlc_second_rejected(true);
9799 }
9800
9801 #[test]
9802 fn test_dup_htlc_second_rejected() {
9803         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9804         // simply reject the second HTLC but are still able to claim the first HTLC.
9805         do_test_dup_htlc_second_rejected(false);
9806 }
9807
9808 #[test]
9809 fn test_inconsistent_mpp_params() {
9810         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9811         // such HTLC and allow the second to stay.
9812         let chanmon_cfgs = create_chanmon_cfgs(4);
9813         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9814         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9815         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9816
9817         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9818         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9819         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9820         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9821
9822         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9823                 .with_features(InvoiceFeatures::known());
9824         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9825         assert_eq!(route.paths.len(), 2);
9826         route.paths.sort_by(|path_a, _| {
9827                 // Sort the path so that the path through nodes[1] comes first
9828                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9829                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9830         });
9831         let payment_params_opt = Some(payment_params);
9832
9833         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9834
9835         let cur_height = nodes[0].best_block_info().1;
9836         let payment_id = PaymentId([42; 32]);
9837         {
9838                 nodes[0].node.send_payment_along_path(&route.paths[0], &payment_params_opt, &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None).unwrap();
9839                 check_added_monitors!(nodes[0], 1);
9840
9841                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9842                 assert_eq!(events.len(), 1);
9843                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9844         }
9845         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9846
9847         {
9848                 nodes[0].node.send_payment_along_path(&route.paths[1], &payment_params_opt, &our_payment_hash, &Some(our_payment_secret), 14_000_000, cur_height, payment_id, &None).unwrap();
9849                 check_added_monitors!(nodes[0], 1);
9850
9851                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9852                 assert_eq!(events.len(), 1);
9853                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9854
9855                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9856                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9857
9858                 expect_pending_htlcs_forwardable!(nodes[2]);
9859                 check_added_monitors!(nodes[2], 1);
9860
9861                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9862                 assert_eq!(events.len(), 1);
9863                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9864
9865                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9866                 check_added_monitors!(nodes[3], 0);
9867                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9868
9869                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9870                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9871                 // post-payment_secrets) and fail back the new HTLC.
9872         }
9873         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9874         nodes[3].node.process_pending_htlc_forwards();
9875         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9876         nodes[3].node.process_pending_htlc_forwards();
9877
9878         check_added_monitors!(nodes[3], 1);
9879
9880         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9881         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9882         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9883
9884         expect_pending_htlcs_forwardable!(nodes[2]);
9885         check_added_monitors!(nodes[2], 1);
9886
9887         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9888         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9889         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9890
9891         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9892
9893         nodes[0].node.send_payment_along_path(&route.paths[1], &payment_params_opt, &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None).unwrap();
9894         check_added_monitors!(nodes[0], 1);
9895
9896         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9897         assert_eq!(events.len(), 1);
9898         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9899
9900         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9901 }
9902
9903 #[test]
9904 fn test_keysend_payments_to_public_node() {
9905         let chanmon_cfgs = create_chanmon_cfgs(2);
9906         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9907         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9908         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9909
9910         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9911         let network_graph = nodes[0].network_graph;
9912         let payer_pubkey = nodes[0].node.get_our_node_id();
9913         let payee_pubkey = nodes[1].node.get_our_node_id();
9914         let route_params = RouteParameters {
9915                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9916                 final_value_msat: 10000,
9917                 final_cltv_expiry_delta: 40,
9918         };
9919         let scorer = test_utils::TestScorer::with_penalty(0);
9920         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9921         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9922
9923         let test_preimage = PaymentPreimage([42; 32]);
9924         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9925         check_added_monitors!(nodes[0], 1);
9926         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9927         assert_eq!(events.len(), 1);
9928         let event = events.pop().unwrap();
9929         let path = vec![&nodes[1]];
9930         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9931         claim_payment(&nodes[0], &path, test_preimage);
9932 }
9933
9934 #[test]
9935 fn test_keysend_payments_to_private_node() {
9936         let chanmon_cfgs = create_chanmon_cfgs(2);
9937         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9938         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9939         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9940
9941         let payer_pubkey = nodes[0].node.get_our_node_id();
9942         let payee_pubkey = nodes[1].node.get_our_node_id();
9943         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9944         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9945
9946         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9947         let route_params = RouteParameters {
9948                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9949                 final_value_msat: 10000,
9950                 final_cltv_expiry_delta: 40,
9951         };
9952         let network_graph = nodes[0].network_graph;
9953         let first_hops = nodes[0].node.list_usable_channels();
9954         let scorer = test_utils::TestScorer::with_penalty(0);
9955         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9956         let route = find_route(
9957                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9958                 nodes[0].logger, &scorer, &random_seed_bytes
9959         ).unwrap();
9960
9961         let test_preimage = PaymentPreimage([42; 32]);
9962         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9963         check_added_monitors!(nodes[0], 1);
9964         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9965         assert_eq!(events.len(), 1);
9966         let event = events.pop().unwrap();
9967         let path = vec![&nodes[1]];
9968         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9969         claim_payment(&nodes[0], &path, test_preimage);
9970 }
9971
9972 #[test]
9973 fn test_double_partial_claim() {
9974         // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9975         // time out, the sender resends only some of the MPP parts, then the user processes the
9976         // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9977         // amount.
9978         let chanmon_cfgs = create_chanmon_cfgs(4);
9979         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9980         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9981         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9982
9983         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9984         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9985         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9986         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9987
9988         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9989         assert_eq!(route.paths.len(), 2);
9990         route.paths.sort_by(|path_a, _| {
9991                 // Sort the path so that the path through nodes[1] comes first
9992                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9993                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9994         });
9995
9996         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9997         // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
9998         // amount of time to respond to.
9999
10000         // Connect some blocks to time out the payment
10001         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
10002         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
10003
10004         expect_pending_htlcs_forwardable!(nodes[3]);
10005
10006         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
10007
10008         // nodes[1] now retries one of the two paths...
10009         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10010         check_added_monitors!(nodes[0], 2);
10011
10012         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10013         assert_eq!(events.len(), 2);
10014         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10015
10016         // At this point nodes[3] has received one half of the payment, and the user goes to handle
10017         // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
10018         nodes[3].node.claim_funds(payment_preimage);
10019         check_added_monitors!(nodes[3], 0);
10020         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
10021 }
10022
10023 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10024         // Test what happens if a node receives an MPP payment, claims it, but crashes before
10025         // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10026         // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10027         // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10028         // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10029         // not have the preimage tied to the still-pending HTLC.
10030         //
10031         // To get to the correct state, on startup we should propagate the preimage to the
10032         // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10033         // receiving the preimage without a state update.
10034         //
10035         // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10036         // definitely claimed.
10037         let chanmon_cfgs = create_chanmon_cfgs(4);
10038         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10039         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10040
10041         let persister: test_utils::TestPersister;
10042         let new_chain_monitor: test_utils::TestChainMonitor;
10043         let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10044
10045         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10046
10047         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10048         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10049         let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10050         let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10051
10052         // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10053         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10054         assert_eq!(route.paths.len(), 2);
10055         route.paths.sort_by(|path_a, _| {
10056                 // Sort the path so that the path through nodes[1] comes first
10057                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10058                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10059         });
10060
10061         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10062         check_added_monitors!(nodes[0], 2);
10063
10064         // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10065         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10066         assert_eq!(send_events.len(), 2);
10067         do_pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[0].clone(), true, false, None);
10068         do_pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[1].clone(), true, false, None);
10069
10070         // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10071         // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10072         let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10073         if !persist_both_monitors {
10074                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10075                         if outpoint.to_channel_id() == chan_id_not_persisted {
10076                                 assert!(original_monitor.0.is_empty());
10077                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10078                         }
10079                 }
10080         }
10081
10082         let mut original_manager = test_utils::TestVecWriter(Vec::new());
10083         nodes[3].node.write(&mut original_manager).unwrap();
10084
10085         expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10086
10087         nodes[3].node.claim_funds(payment_preimage);
10088         check_added_monitors!(nodes[3], 2);
10089         expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10090
10091         // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10092         // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10093         // with the old ChannelManager.
10094         let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10095         for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10096                 if outpoint.to_channel_id() == chan_id_persisted {
10097                         assert!(updated_monitor.0.is_empty());
10098                         nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10099                 }
10100         }
10101         // If `persist_both_monitors` is set, get the second monitor here as well
10102         if persist_both_monitors {
10103                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10104                         if outpoint.to_channel_id() == chan_id_not_persisted {
10105                                 assert!(original_monitor.0.is_empty());
10106                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10107                         }
10108                 }
10109         }
10110
10111         // Now restart nodes[3].
10112         persister = test_utils::TestPersister::new();
10113         let keys_manager = &chanmon_cfgs[3].keys_manager;
10114         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[3].chain_source), nodes[3].tx_broadcaster.clone(), nodes[3].logger, node_cfgs[3].fee_estimator, &persister, keys_manager);
10115         nodes[3].chain_monitor = &new_chain_monitor;
10116         let mut monitors = Vec::new();
10117         for mut monitor_data in [original_monitor, updated_monitor].iter() {
10118                 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10119                 monitors.push(deserialized_monitor);
10120         }
10121
10122         let config = UserConfig::default();
10123         nodes_3_deserialized = {
10124                 let mut channel_monitors = HashMap::new();
10125                 for monitor in monitors.iter_mut() {
10126                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10127                 }
10128                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10129                         default_config: config,
10130                         keys_manager,
10131                         fee_estimator: node_cfgs[3].fee_estimator,
10132                         chain_monitor: nodes[3].chain_monitor,
10133                         tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10134                         logger: nodes[3].logger,
10135                         channel_monitors,
10136                 }).unwrap().1
10137         };
10138         nodes[3].node = &nodes_3_deserialized;
10139
10140         for monitor in monitors {
10141                 // On startup the preimage should have been copied into the non-persisted monitor:
10142                 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10143                 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10144         }
10145         check_added_monitors!(nodes[3], 2);
10146
10147         nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10148         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10149
10150         // During deserialization, we should have closed one channel and broadcast its latest
10151         // commitment transaction. We should also still have the original PaymentReceived event we
10152         // never finished processing.
10153         let events = nodes[3].node.get_and_clear_pending_events();
10154         assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10155         if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10156         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10157         if persist_both_monitors {
10158                 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10159         }
10160
10161         // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10162         // ChannelManager prior to handling the original one.
10163         if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10164                 events[if persist_both_monitors { 3 } else { 2 }]
10165         {
10166                 assert_eq!(payment_hash, our_payment_hash);
10167         } else { panic!(); }
10168
10169         assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10170         if !persist_both_monitors {
10171                 // If one of the two channels is still live, reveal the payment preimage over it.
10172
10173                 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10174                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10175                 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10176                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10177
10178                 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10179                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10180                 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10181
10182                 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10183
10184                 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10185                 // claim should fly.
10186                 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10187                 check_added_monitors!(nodes[3], 1);
10188                 assert_eq!(ds_msgs.len(), 2);
10189                 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10190
10191                 let cs_updates = match ds_msgs[0] {
10192                         MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10193                                 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10194                                 check_added_monitors!(nodes[2], 1);
10195                                 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10196                                 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10197                                 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10198                                 cs_updates
10199                         }
10200                         _ => panic!(),
10201                 };
10202
10203                 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10204                 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10205                 expect_payment_sent!(nodes[0], payment_preimage);
10206         }
10207 }
10208
10209 #[test]
10210 fn test_partial_claim_before_restart() {
10211         do_test_partial_claim_before_restart(false);
10212         do_test_partial_claim_before_restart(true);
10213 }
10214
10215 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10216 #[derive(Clone, Copy, PartialEq)]
10217 enum ExposureEvent {
10218         /// Breach occurs at HTLC forwarding (see `send_htlc`)
10219         AtHTLCForward,
10220         /// Breach occurs at HTLC reception (see `update_add_htlc`)
10221         AtHTLCReception,
10222         /// Breach occurs at outbound update_fee (see `send_update_fee`)
10223         AtUpdateFeeOutbound,
10224 }
10225
10226 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10227         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10228         // policy.
10229         //
10230         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10231         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10232         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10233         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10234         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10235         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10236         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10237         // might be available again for HTLC processing once the dust bandwidth has cleared up.
10238
10239         let chanmon_cfgs = create_chanmon_cfgs(2);
10240         let mut config = test_default_channel_config();
10241         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10242         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10243         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10244         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10245
10246         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10247         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10248         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10249         open_channel.max_accepted_htlcs = 60;
10250         if on_holder_tx {
10251                 open_channel.dust_limit_satoshis = 546;
10252         }
10253         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10254         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10255         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10256
10257         let opt_anchors = false;
10258
10259         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10260
10261         if on_holder_tx {
10262                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10263                         chan.holder_dust_limit_satoshis = 546;
10264                 }
10265         }
10266
10267         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10268         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()));
10269         check_added_monitors!(nodes[1], 1);
10270
10271         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()));
10272         check_added_monitors!(nodes[0], 1);
10273
10274         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10275         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10276         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10277
10278         let dust_buffer_feerate = {
10279                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10280                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10281                 chan.get_dust_buffer_feerate(None) as u64
10282         };
10283         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;
10284         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10285
10286         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;
10287         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10288
10289         let dust_htlc_on_counterparty_tx: u64 = 25;
10290         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10291
10292         if on_holder_tx {
10293                 if dust_outbound_balance {
10294                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10295                         // Outbound dust balance: 4372 sats
10296                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10297                         for i in 0..dust_outbound_htlc_on_holder_tx {
10298                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10299                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10300                         }
10301                 } else {
10302                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10303                         // Inbound dust balance: 4372 sats
10304                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10305                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10306                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10307                         }
10308                 }
10309         } else {
10310                 if dust_outbound_balance {
10311                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10312                         // Outbound dust balance: 5000 sats
10313                         for i in 0..dust_htlc_on_counterparty_tx {
10314                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10315                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10316                         }
10317                 } else {
10318                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10319                         // Inbound dust balance: 5000 sats
10320                         for _ in 0..dust_htlc_on_counterparty_tx {
10321                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10322                         }
10323                 }
10324         }
10325
10326         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10327         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10328                 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 });
10329                 let mut config = UserConfig::default();
10330                 // With default dust exposure: 5000 sats
10331                 if on_holder_tx {
10332                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10333                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10334                         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_config.max_dust_htlc_exposure_msat)));
10335                 } else {
10336                         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_config.max_dust_htlc_exposure_msat)));
10337                 }
10338         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10339                 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 });
10340                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10341                 check_added_monitors!(nodes[1], 1);
10342                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10343                 assert_eq!(events.len(), 1);
10344                 let payment_event = SendEvent::from_event(events.remove(0));
10345                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10346                 // With default dust exposure: 5000 sats
10347                 if on_holder_tx {
10348                         // Outbound dust balance: 6399 sats
10349                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10350                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10351                         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_config.max_dust_htlc_exposure_msat), 1);
10352                 } else {
10353                         // Outbound dust balance: 5200 sats
10354                         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_config.max_dust_htlc_exposure_msat), 1);
10355                 }
10356         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10357                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10358                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10359                 {
10360                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10361                         *feerate_lock = *feerate_lock * 10;
10362                 }
10363                 nodes[0].node.timer_tick_occurred();
10364                 check_added_monitors!(nodes[0], 1);
10365                 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);
10366         }
10367
10368         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10369         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10370         added_monitors.clear();
10371 }
10372
10373 #[test]
10374 fn test_max_dust_htlc_exposure() {
10375         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10376         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10377         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10378         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10379         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10380         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10381         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10382         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10383         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10384         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10385         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10386         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10387 }
10388
10389 #[test]
10390 fn test_non_final_funding_tx() {
10391         let chanmon_cfgs = create_chanmon_cfgs(2);
10392         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10393         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10394         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10395
10396         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10397         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10398         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
10399         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10400         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
10401
10402         let best_height = nodes[0].node.best_block.read().unwrap().height();
10403
10404         let chan_id = *nodes[0].network_chan_count.borrow();
10405         let events = nodes[0].node.get_and_clear_pending_events();
10406         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: 0x1, witness: Witness::from_vec(vec!(vec!(1))) };
10407         assert_eq!(events.len(), 1);
10408         let mut tx = match events[0] {
10409                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10410                         // Timelock the transaction _beyond_ the best client height + 2.
10411                         Transaction { version: chan_id as i32, lock_time: best_height + 3, input: vec![input], output: vec![TxOut {
10412                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10413                         }]}
10414                 },
10415                 _ => panic!("Unexpected event"),
10416         };
10417         // Transaction should fail as it's evaluated as non-final for propagation.
10418         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10419                 Err(APIError::APIMisuseError { err }) => {
10420                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10421                 },
10422                 _ => panic!()
10423         }
10424
10425         // However, transaction should be accepted if it's in a +2 headroom from best block.
10426         tx.lock_time -= 1;
10427         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10428         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10429 }