Merge pull request #1605 from TheBlueMatt/2022-07-smaller-mpp-parts
[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::chaininterface::LowerBoundedFeeEstimator;
17 use chain::channelmonitor;
18 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use chain::transaction::OutPoint;
20 use chain::keysinterface::{BaseSign, KeysInterface};
21 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
22 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};
23 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS };
24 use ln::channel::{Channel, ChannelError};
25 use ln::{chan_utils, onion_utils};
26 use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
27 use routing::gossip::NetworkGraph;
28 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
29 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
30 use ln::msgs;
31 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, OptionalField, ErrorAction};
32 use util::enforcing_trait_impls::EnforcingSigner;
33 use util::{byte_utils, test_utils};
34 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
35 use util::errors::APIError;
36 use util::ser::{Writeable, ReadableArgs};
37 use util::config::UserConfig;
38
39 use bitcoin::hash_types::BlockHash;
40 use bitcoin::blockdata::block::{Block, BlockHeader};
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
47
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
50
51 use regex;
52
53 use io;
54 use prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use sync::{Arc, Mutex};
58
59 use ln::functional_test_utils::*;
60 use ln::chan_utils::CommitmentTransaction;
61
62 #[test]
63 fn test_insane_channel_opens() {
64         // Stand up a network of 2 nodes
65         use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
66         let mut cfg = UserConfig::default();
67         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
68         let chanmon_cfgs = create_chanmon_cfgs(2);
69         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
70         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
71         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
72
73         // Instantiate channel parameters where we push the maximum msats given our
74         // funding satoshis
75         let channel_value_sat = 31337; // same as funding satoshis
76         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
77         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
78
79         // Have node0 initiate a channel to node1 with aforementioned parameters
80         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
81
82         // Extract the channel open message from node0 to node1
83         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
84
85         // Test helper that asserts we get the correct error string given a mutator
86         // that supposedly makes the channel open message insane
87         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
88                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
89                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
90                 assert_eq!(msg_events.len(), 1);
91                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
92                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
93                         match action {
94                                 &ErrorAction::SendErrorMessage { .. } => {
95                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
96                                 },
97                                 _ => panic!("unexpected event!"),
98                         }
99                 } else { assert!(false); }
100         };
101
102         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
103
104         // Test all mutations that would make the channel open message insane
105         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 });
106         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 });
107
108         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
109
110         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 });
111
112         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
113
114         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 });
115
116         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 });
117
118         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
119
120         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
121 }
122
123 #[test]
124 fn test_funding_exceeds_no_wumbo_limit() {
125         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
126         // them.
127         use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
128         let chanmon_cfgs = create_chanmon_cfgs(2);
129         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
130         node_cfgs[1].features = InitFeatures::known().clear_wumbo();
131         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
132         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
133
134         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
135                 Err(APIError::APIMisuseError { err }) => {
136                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
137                 },
138                 _ => panic!()
139         }
140 }
141
142 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
143         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
144         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
145         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
146         // in normal testing, we test it explicitly here.
147         let chanmon_cfgs = create_chanmon_cfgs(2);
148         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
149         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
150         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
151
152         // Have node0 initiate a channel to node1 with aforementioned parameters
153         let mut push_amt = 100_000_000;
154         let feerate_per_kw = 253;
155         let opt_anchors = false;
156         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
157         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
158
159         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();
160         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
161         if !send_from_initiator {
162                 open_channel_message.channel_reserve_satoshis = 0;
163                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
164         }
165         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
166
167         // Extract the channel accept message from node1 to node0
168         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
169         if send_from_initiator {
170                 accept_channel_message.channel_reserve_satoshis = 0;
171                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
172         }
173         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
174         {
175                 let mut lock;
176                 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
177                 chan.holder_selected_channel_reserve_satoshis = 0;
178                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
179         }
180
181         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
182         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
183         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
184
185         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
186         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
187         if send_from_initiator {
188                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
189                         // Note that for outbound channels we have to consider the commitment tx fee and the
190                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
191                         // well as an additional HTLC.
192                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
193         } else {
194                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
195         }
196 }
197
198 #[test]
199 fn test_counterparty_no_reserve() {
200         do_test_counterparty_no_reserve(true);
201         do_test_counterparty_no_reserve(false);
202 }
203
204 #[test]
205 fn test_async_inbound_update_fee() {
206         let chanmon_cfgs = create_chanmon_cfgs(2);
207         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
208         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
209         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
210         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
211
212         // balancing
213         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
214
215         // A                                        B
216         // update_fee                            ->
217         // send (1) commitment_signed            -.
218         //                                       <- update_add_htlc/commitment_signed
219         // send (2) RAA (awaiting remote revoke) -.
220         // (1) commitment_signed is delivered    ->
221         //                                       .- send (3) RAA (awaiting remote revoke)
222         // (2) RAA is delivered                  ->
223         //                                       .- send (4) commitment_signed
224         //                                       <- (3) RAA is delivered
225         // send (5) commitment_signed            -.
226         //                                       <- (4) commitment_signed is delivered
227         // send (6) RAA                          -.
228         // (5) commitment_signed is delivered    ->
229         //                                       <- RAA
230         // (6) RAA is delivered                  ->
231
232         // First nodes[0] generates an update_fee
233         {
234                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
235                 *feerate_lock += 20;
236         }
237         nodes[0].node.timer_tick_occurred();
238         check_added_monitors!(nodes[0], 1);
239
240         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
241         assert_eq!(events_0.len(), 1);
242         let (update_msg, commitment_signed) = match events_0[0] { // (1)
243                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
244                         (update_fee.as_ref(), commitment_signed)
245                 },
246                 _ => panic!("Unexpected event"),
247         };
248
249         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
250
251         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
252         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
253         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
254         check_added_monitors!(nodes[1], 1);
255
256         let payment_event = {
257                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
258                 assert_eq!(events_1.len(), 1);
259                 SendEvent::from_event(events_1.remove(0))
260         };
261         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
262         assert_eq!(payment_event.msgs.len(), 1);
263
264         // ...now when the messages get delivered everyone should be happy
265         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
266         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
267         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
268         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
269         check_added_monitors!(nodes[0], 1);
270
271         // deliver(1), generate (3):
272         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
273         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
274         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
275         check_added_monitors!(nodes[1], 1);
276
277         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
278         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
279         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
280         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
281         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
282         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
283         assert!(bs_update.update_fee.is_none()); // (4)
284         check_added_monitors!(nodes[1], 1);
285
286         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
287         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
288         assert!(as_update.update_add_htlcs.is_empty()); // (5)
289         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
290         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
291         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
292         assert!(as_update.update_fee.is_none()); // (5)
293         check_added_monitors!(nodes[0], 1);
294
295         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
296         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
297         // only (6) so get_event_msg's assert(len == 1) passes
298         check_added_monitors!(nodes[0], 1);
299
300         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
301         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
302         check_added_monitors!(nodes[1], 1);
303
304         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
305         check_added_monitors!(nodes[0], 1);
306
307         let events_2 = nodes[0].node.get_and_clear_pending_events();
308         assert_eq!(events_2.len(), 1);
309         match events_2[0] {
310                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
311                 _ => panic!("Unexpected event"),
312         }
313
314         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
315         check_added_monitors!(nodes[1], 1);
316 }
317
318 #[test]
319 fn test_update_fee_unordered_raa() {
320         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
321         // crash in an earlier version of the update_fee patch)
322         let chanmon_cfgs = create_chanmon_cfgs(2);
323         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
324         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
325         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
326         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
327
328         // balancing
329         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
330
331         // First nodes[0] generates an update_fee
332         {
333                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
334                 *feerate_lock += 20;
335         }
336         nodes[0].node.timer_tick_occurred();
337         check_added_monitors!(nodes[0], 1);
338
339         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
340         assert_eq!(events_0.len(), 1);
341         let update_msg = match events_0[0] { // (1)
342                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
343                         update_fee.as_ref()
344                 },
345                 _ => panic!("Unexpected event"),
346         };
347
348         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
349
350         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
351         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
352         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
353         check_added_monitors!(nodes[1], 1);
354
355         let payment_event = {
356                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
357                 assert_eq!(events_1.len(), 1);
358                 SendEvent::from_event(events_1.remove(0))
359         };
360         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
361         assert_eq!(payment_event.msgs.len(), 1);
362
363         // ...now when the messages get delivered everyone should be happy
364         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
365         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
366         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
367         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
368         check_added_monitors!(nodes[0], 1);
369
370         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
371         check_added_monitors!(nodes[1], 1);
372
373         // We can't continue, sadly, because our (1) now has a bogus signature
374 }
375
376 #[test]
377 fn test_multi_flight_update_fee() {
378         let chanmon_cfgs = create_chanmon_cfgs(2);
379         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
380         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
381         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
382         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
383
384         // A                                        B
385         // update_fee/commitment_signed          ->
386         //                                       .- send (1) RAA and (2) commitment_signed
387         // update_fee (never committed)          ->
388         // (3) update_fee                        ->
389         // We have to manually generate the above update_fee, it is allowed by the protocol but we
390         // don't track which updates correspond to which revoke_and_ack responses so we're in
391         // AwaitingRAA mode and will not generate the update_fee yet.
392         //                                       <- (1) RAA delivered
393         // (3) is generated and send (4) CS      -.
394         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
395         // know the per_commitment_point to use for it.
396         //                                       <- (2) commitment_signed delivered
397         // revoke_and_ack                        ->
398         //                                          B should send no response here
399         // (4) commitment_signed delivered       ->
400         //                                       <- RAA/commitment_signed delivered
401         // revoke_and_ack                        ->
402
403         // First nodes[0] generates an update_fee
404         let initial_feerate;
405         {
406                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
407                 initial_feerate = *feerate_lock;
408                 *feerate_lock = initial_feerate + 20;
409         }
410         nodes[0].node.timer_tick_occurred();
411         check_added_monitors!(nodes[0], 1);
412
413         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
414         assert_eq!(events_0.len(), 1);
415         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
416                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
417                         (update_fee.as_ref().unwrap(), commitment_signed)
418                 },
419                 _ => panic!("Unexpected event"),
420         };
421
422         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
423         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
424         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
425         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
426         check_added_monitors!(nodes[1], 1);
427
428         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
429         // transaction:
430         {
431                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
432                 *feerate_lock = initial_feerate + 40;
433         }
434         nodes[0].node.timer_tick_occurred();
435         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
436         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
437
438         // Create the (3) update_fee message that nodes[0] will generate before it does...
439         let mut update_msg_2 = msgs::UpdateFee {
440                 channel_id: update_msg_1.channel_id.clone(),
441                 feerate_per_kw: (initial_feerate + 30) as u32,
442         };
443
444         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
445
446         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
447         // Deliver (3)
448         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
449
450         // Deliver (1), generating (3) and (4)
451         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
452         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
453         check_added_monitors!(nodes[0], 1);
454         assert!(as_second_update.update_add_htlcs.is_empty());
455         assert!(as_second_update.update_fulfill_htlcs.is_empty());
456         assert!(as_second_update.update_fail_htlcs.is_empty());
457         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
458         // Check that the update_fee newly generated matches what we delivered:
459         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
460         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
461
462         // Deliver (2) commitment_signed
463         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
464         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
465         check_added_monitors!(nodes[0], 1);
466         // No commitment_signed so get_event_msg's assert(len == 1) passes
467
468         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
469         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
470         check_added_monitors!(nodes[1], 1);
471
472         // Delever (4)
473         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
474         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
475         check_added_monitors!(nodes[1], 1);
476
477         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
478         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
479         check_added_monitors!(nodes[0], 1);
480
481         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
482         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
483         // No commitment_signed so get_event_msg's assert(len == 1) passes
484         check_added_monitors!(nodes[0], 1);
485
486         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
487         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
488         check_added_monitors!(nodes[1], 1);
489 }
490
491 fn do_test_sanity_on_in_flight_opens(steps: u8) {
492         // Previously, we had issues deserializing channels when we hadn't connected the first block
493         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
494         // serialization round-trips and simply do steps towards opening a channel and then drop the
495         // Node objects.
496
497         let chanmon_cfgs = create_chanmon_cfgs(2);
498         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
499         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
500         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
501
502         if steps & 0b1000_0000 != 0{
503                 let block = Block {
504                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
505                         txdata: vec![],
506                 };
507                 connect_block(&nodes[0], &block);
508                 connect_block(&nodes[1], &block);
509         }
510
511         if steps & 0x0f == 0 { return; }
512         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
513         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
514
515         if steps & 0x0f == 1 { return; }
516         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
517         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
518
519         if steps & 0x0f == 2 { return; }
520         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
521
522         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
523
524         if steps & 0x0f == 3 { return; }
525         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
526         check_added_monitors!(nodes[0], 0);
527         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
528
529         if steps & 0x0f == 4 { return; }
530         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
531         {
532                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
533                 assert_eq!(added_monitors.len(), 1);
534                 assert_eq!(added_monitors[0].0, funding_output);
535                 added_monitors.clear();
536         }
537         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
538
539         if steps & 0x0f == 5 { return; }
540         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
541         {
542                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
543                 assert_eq!(added_monitors.len(), 1);
544                 assert_eq!(added_monitors[0].0, funding_output);
545                 added_monitors.clear();
546         }
547
548         let events_4 = nodes[0].node.get_and_clear_pending_events();
549         assert_eq!(events_4.len(), 0);
550
551         if steps & 0x0f == 6 { return; }
552         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
553
554         if steps & 0x0f == 7 { return; }
555         confirm_transaction_at(&nodes[0], &tx, 2);
556         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
557         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
558 }
559
560 #[test]
561 fn test_sanity_on_in_flight_opens() {
562         do_test_sanity_on_in_flight_opens(0);
563         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
564         do_test_sanity_on_in_flight_opens(1);
565         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
566         do_test_sanity_on_in_flight_opens(2);
567         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
568         do_test_sanity_on_in_flight_opens(3);
569         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
570         do_test_sanity_on_in_flight_opens(4);
571         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
572         do_test_sanity_on_in_flight_opens(5);
573         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
574         do_test_sanity_on_in_flight_opens(6);
575         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
576         do_test_sanity_on_in_flight_opens(7);
577         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
578         do_test_sanity_on_in_flight_opens(8);
579         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
580 }
581
582 #[test]
583 fn test_update_fee_vanilla() {
584         let chanmon_cfgs = create_chanmon_cfgs(2);
585         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
586         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
587         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
588         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
589
590         {
591                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
592                 *feerate_lock += 25;
593         }
594         nodes[0].node.timer_tick_occurred();
595         check_added_monitors!(nodes[0], 1);
596
597         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
598         assert_eq!(events_0.len(), 1);
599         let (update_msg, commitment_signed) = match events_0[0] {
600                         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 } } => {
601                         (update_fee.as_ref(), commitment_signed)
602                 },
603                 _ => panic!("Unexpected event"),
604         };
605         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
606
607         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
608         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
609         check_added_monitors!(nodes[1], 1);
610
611         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
612         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
613         check_added_monitors!(nodes[0], 1);
614
615         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
616         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
617         // No commitment_signed so get_event_msg's assert(len == 1) passes
618         check_added_monitors!(nodes[0], 1);
619
620         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
621         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
622         check_added_monitors!(nodes[1], 1);
623 }
624
625 #[test]
626 fn test_update_fee_that_funder_cannot_afford() {
627         let chanmon_cfgs = create_chanmon_cfgs(2);
628         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
629         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
630         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
631         let channel_value = 5000;
632         let push_sats = 700;
633         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
634         let channel_id = chan.2;
635         let secp_ctx = Secp256k1::new();
636         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
637
638         let opt_anchors = false;
639
640         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
641         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
642         // calculate two different feerates here - the expected local limit as well as the expected
643         // remote limit.
644         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;
645         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
646         {
647                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
648                 *feerate_lock = feerate;
649         }
650         nodes[0].node.timer_tick_occurred();
651         check_added_monitors!(nodes[0], 1);
652         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
653
654         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
655
656         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
657
658         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
659         {
660                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
661
662                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
663                 assert_eq!(commitment_tx.output.len(), 2);
664                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
665                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
666                 actual_fee = channel_value - actual_fee;
667                 assert_eq!(total_fee, actual_fee);
668         }
669
670         {
671                 // Increment the feerate by a small constant, accounting for rounding errors
672                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
673                 *feerate_lock += 4;
674         }
675         nodes[0].node.timer_tick_occurred();
676         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
677         check_added_monitors!(nodes[0], 0);
678
679         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
680
681         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
682         // needed to sign the new commitment tx and (2) sign the new commitment tx.
683         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
684                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
685                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
686                 let chan_signer = local_chan.get_signer();
687                 let pubkeys = chan_signer.pubkeys();
688                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
689                  pubkeys.funding_pubkey)
690         };
691         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
692                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
693                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
694                 let chan_signer = remote_chan.get_signer();
695                 let pubkeys = chan_signer.pubkeys();
696                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
697                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
698                  pubkeys.funding_pubkey)
699         };
700
701         // Assemble the set of keys we can use for signatures for our commitment_signed message.
702         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
703                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
704
705         let res = {
706                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
707                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
708                 let local_chan_signer = local_chan.get_signer();
709                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
710                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
711                         INITIAL_COMMITMENT_NUMBER - 1,
712                         push_sats,
713                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
714                         opt_anchors, local_funding, remote_funding,
715                         commit_tx_keys.clone(),
716                         non_buffer_feerate + 4,
717                         &mut htlcs,
718                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
719                 );
720                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
721         };
722
723         let commit_signed_msg = msgs::CommitmentSigned {
724                 channel_id: chan.2,
725                 signature: res.0,
726                 htlc_signatures: res.1
727         };
728
729         let update_fee = msgs::UpdateFee {
730                 channel_id: chan.2,
731                 feerate_per_kw: non_buffer_feerate + 4,
732         };
733
734         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
735
736         //While producing the commitment_signed response after handling a received update_fee request the
737         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
738         //Should produce and error.
739         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
740         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
741         check_added_monitors!(nodes[1], 1);
742         check_closed_broadcast!(nodes[1], true);
743         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
744 }
745
746 #[test]
747 fn test_update_fee_with_fundee_update_add_htlc() {
748         let chanmon_cfgs = create_chanmon_cfgs(2);
749         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
750         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
751         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
752         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
753
754         // balancing
755         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
756
757         {
758                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
759                 *feerate_lock += 20;
760         }
761         nodes[0].node.timer_tick_occurred();
762         check_added_monitors!(nodes[0], 1);
763
764         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
765         assert_eq!(events_0.len(), 1);
766         let (update_msg, commitment_signed) = match events_0[0] {
767                         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 } } => {
768                         (update_fee.as_ref(), commitment_signed)
769                 },
770                 _ => panic!("Unexpected event"),
771         };
772         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
773         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
774         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
775         check_added_monitors!(nodes[1], 1);
776
777         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
778
779         // nothing happens since node[1] is in AwaitingRemoteRevoke
780         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
781         {
782                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
783                 assert_eq!(added_monitors.len(), 0);
784                 added_monitors.clear();
785         }
786         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
787         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
788         // node[1] has nothing to do
789
790         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
791         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
792         check_added_monitors!(nodes[0], 1);
793
794         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
795         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
796         // No commitment_signed so get_event_msg's assert(len == 1) passes
797         check_added_monitors!(nodes[0], 1);
798         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
799         check_added_monitors!(nodes[1], 1);
800         // AwaitingRemoteRevoke ends here
801
802         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
803         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
804         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
805         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
806         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
807         assert_eq!(commitment_update.update_fee.is_none(), true);
808
809         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
810         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
811         check_added_monitors!(nodes[0], 1);
812         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
813
814         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
815         check_added_monitors!(nodes[1], 1);
816         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
817
818         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
819         check_added_monitors!(nodes[1], 1);
820         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
821         // No commitment_signed so get_event_msg's assert(len == 1) passes
822
823         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
824         check_added_monitors!(nodes[0], 1);
825         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
826
827         expect_pending_htlcs_forwardable!(nodes[0]);
828
829         let events = nodes[0].node.get_and_clear_pending_events();
830         assert_eq!(events.len(), 1);
831         match events[0] {
832                 Event::PaymentReceived { .. } => { },
833                 _ => panic!("Unexpected event"),
834         };
835
836         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
837
838         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
839         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
840         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
841         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
842         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
843 }
844
845 #[test]
846 fn test_update_fee() {
847         let chanmon_cfgs = create_chanmon_cfgs(2);
848         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
849         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
850         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
851         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
852         let channel_id = chan.2;
853
854         // A                                        B
855         // (1) update_fee/commitment_signed      ->
856         //                                       <- (2) revoke_and_ack
857         //                                       .- send (3) commitment_signed
858         // (4) update_fee/commitment_signed      ->
859         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
860         //                                       <- (3) commitment_signed delivered
861         // send (6) revoke_and_ack               -.
862         //                                       <- (5) deliver revoke_and_ack
863         // (6) deliver revoke_and_ack            ->
864         //                                       .- send (7) commitment_signed in response to (4)
865         //                                       <- (7) deliver commitment_signed
866         // revoke_and_ack                        ->
867
868         // Create and deliver (1)...
869         let feerate;
870         {
871                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
872                 feerate = *feerate_lock;
873                 *feerate_lock = feerate + 20;
874         }
875         nodes[0].node.timer_tick_occurred();
876         check_added_monitors!(nodes[0], 1);
877
878         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
879         assert_eq!(events_0.len(), 1);
880         let (update_msg, commitment_signed) = match events_0[0] {
881                         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 } } => {
882                         (update_fee.as_ref(), commitment_signed)
883                 },
884                 _ => panic!("Unexpected event"),
885         };
886         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
887
888         // Generate (2) and (3):
889         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
890         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
891         check_added_monitors!(nodes[1], 1);
892
893         // Deliver (2):
894         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
895         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
896         check_added_monitors!(nodes[0], 1);
897
898         // Create and deliver (4)...
899         {
900                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
901                 *feerate_lock = feerate + 30;
902         }
903         nodes[0].node.timer_tick_occurred();
904         check_added_monitors!(nodes[0], 1);
905         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
906         assert_eq!(events_0.len(), 1);
907         let (update_msg, commitment_signed) = match events_0[0] {
908                         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 } } => {
909                         (update_fee.as_ref(), commitment_signed)
910                 },
911                 _ => panic!("Unexpected event"),
912         };
913
914         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
915         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
916         check_added_monitors!(nodes[1], 1);
917         // ... creating (5)
918         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
919         // No commitment_signed so get_event_msg's assert(len == 1) passes
920
921         // Handle (3), creating (6):
922         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
923         check_added_monitors!(nodes[0], 1);
924         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
925         // No commitment_signed so get_event_msg's assert(len == 1) passes
926
927         // Deliver (5):
928         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
929         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
930         check_added_monitors!(nodes[0], 1);
931
932         // Deliver (6), creating (7):
933         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
934         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
935         assert!(commitment_update.update_add_htlcs.is_empty());
936         assert!(commitment_update.update_fulfill_htlcs.is_empty());
937         assert!(commitment_update.update_fail_htlcs.is_empty());
938         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
939         assert!(commitment_update.update_fee.is_none());
940         check_added_monitors!(nodes[1], 1);
941
942         // Deliver (7)
943         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
944         check_added_monitors!(nodes[0], 1);
945         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
946         // No commitment_signed so get_event_msg's assert(len == 1) passes
947
948         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
949         check_added_monitors!(nodes[1], 1);
950         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
951
952         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
953         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
954         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
955         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
956         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
957 }
958
959 #[test]
960 fn fake_network_test() {
961         // Simple test which builds a network of ChannelManagers, connects them to each other, and
962         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
963         let chanmon_cfgs = create_chanmon_cfgs(4);
964         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
965         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
966         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
967
968         // Create some initial channels
969         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
970         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
971         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
972
973         // Rebalance the network a bit by relaying one payment through all the channels...
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         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
978
979         // Send some more payments
980         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
981         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
982         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
983
984         // Test failure packets
985         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
986         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
987
988         // Add a new channel that skips 3
989         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
990
991         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
992         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
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         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
998
999         // Do some rebalance loop payments, simultaneously
1000         let mut hops = Vec::with_capacity(3);
1001         hops.push(RouteHop {
1002                 pubkey: nodes[2].node.get_our_node_id(),
1003                 node_features: NodeFeatures::empty(),
1004                 short_channel_id: chan_2.0.contents.short_channel_id,
1005                 channel_features: ChannelFeatures::empty(),
1006                 fee_msat: 0,
1007                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1008         });
1009         hops.push(RouteHop {
1010                 pubkey: nodes[3].node.get_our_node_id(),
1011                 node_features: NodeFeatures::empty(),
1012                 short_channel_id: chan_3.0.contents.short_channel_id,
1013                 channel_features: ChannelFeatures::empty(),
1014                 fee_msat: 0,
1015                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1016         });
1017         hops.push(RouteHop {
1018                 pubkey: nodes[1].node.get_our_node_id(),
1019                 node_features: NodeFeatures::known(),
1020                 short_channel_id: chan_4.0.contents.short_channel_id,
1021                 channel_features: ChannelFeatures::known(),
1022                 fee_msat: 1000000,
1023                 cltv_expiry_delta: TEST_FINAL_CLTV,
1024         });
1025         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;
1026         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;
1027         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;
1028
1029         let mut hops = Vec::with_capacity(3);
1030         hops.push(RouteHop {
1031                 pubkey: nodes[3].node.get_our_node_id(),
1032                 node_features: NodeFeatures::empty(),
1033                 short_channel_id: chan_4.0.contents.short_channel_id,
1034                 channel_features: ChannelFeatures::empty(),
1035                 fee_msat: 0,
1036                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1037         });
1038         hops.push(RouteHop {
1039                 pubkey: nodes[2].node.get_our_node_id(),
1040                 node_features: NodeFeatures::empty(),
1041                 short_channel_id: chan_3.0.contents.short_channel_id,
1042                 channel_features: ChannelFeatures::empty(),
1043                 fee_msat: 0,
1044                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1045         });
1046         hops.push(RouteHop {
1047                 pubkey: nodes[1].node.get_our_node_id(),
1048                 node_features: NodeFeatures::known(),
1049                 short_channel_id: chan_2.0.contents.short_channel_id,
1050                 channel_features: ChannelFeatures::known(),
1051                 fee_msat: 1000000,
1052                 cltv_expiry_delta: TEST_FINAL_CLTV,
1053         });
1054         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;
1055         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;
1056         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;
1057
1058         // Claim the rebalances...
1059         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1060         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1061
1062         // Add a duplicate new channel from 2 to 4
1063         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1064
1065         // Send some payments across both channels
1066         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1067         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1068         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1069
1070
1071         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1072         let events = nodes[0].node.get_and_clear_pending_msg_events();
1073         assert_eq!(events.len(), 0);
1074         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);
1075
1076         //TODO: Test that routes work again here as we've been notified that the channel is full
1077
1078         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1079         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1080         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1081
1082         // Close down the channels...
1083         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1084         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1085         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1086         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1087         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1088         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1089         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1090         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1091         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1092         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1093         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1094         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1095         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1096         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1097         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1098 }
1099
1100 #[test]
1101 fn holding_cell_htlc_counting() {
1102         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1103         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1104         // commitment dance rounds.
1105         let chanmon_cfgs = create_chanmon_cfgs(3);
1106         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1107         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1108         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1109         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1110         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1111
1112         let mut payments = Vec::new();
1113         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1114                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1115                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1116                 payments.push((payment_preimage, payment_hash));
1117         }
1118         check_added_monitors!(nodes[1], 1);
1119
1120         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1121         assert_eq!(events.len(), 1);
1122         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1123         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1124
1125         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1126         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1127         // another HTLC.
1128         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1129         {
1130                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1131                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1132                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1133                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1134         }
1135
1136         // This should also be true if we try to forward a payment.
1137         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1138         {
1139                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1140                 check_added_monitors!(nodes[0], 1);
1141         }
1142
1143         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1144         assert_eq!(events.len(), 1);
1145         let payment_event = SendEvent::from_event(events.pop().unwrap());
1146         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1147
1148         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1149         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1150         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1151         // fails), the second will process the resulting failure and fail the HTLC backward.
1152         expect_pending_htlcs_forwardable!(nodes[1]);
1153         expect_pending_htlcs_forwardable!(nodes[1]);
1154         check_added_monitors!(nodes[1], 1);
1155
1156         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1157         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1158         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1159
1160         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1161
1162         // Now forward all the pending HTLCs and claim them back
1163         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1164         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1165         check_added_monitors!(nodes[2], 1);
1166
1167         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1168         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1169         check_added_monitors!(nodes[1], 1);
1170         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1171
1172         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1173         check_added_monitors!(nodes[1], 1);
1174         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1175
1176         for ref update in as_updates.update_add_htlcs.iter() {
1177                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1178         }
1179         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1180         check_added_monitors!(nodes[2], 1);
1181         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1182         check_added_monitors!(nodes[2], 1);
1183         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1184
1185         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1186         check_added_monitors!(nodes[1], 1);
1187         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1188         check_added_monitors!(nodes[1], 1);
1189         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1190
1191         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1192         check_added_monitors!(nodes[2], 1);
1193
1194         expect_pending_htlcs_forwardable!(nodes[2]);
1195
1196         let events = nodes[2].node.get_and_clear_pending_events();
1197         assert_eq!(events.len(), payments.len());
1198         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1199                 match event {
1200                         &Event::PaymentReceived { ref payment_hash, .. } => {
1201                                 assert_eq!(*payment_hash, *hash);
1202                         },
1203                         _ => panic!("Unexpected event"),
1204                 };
1205         }
1206
1207         for (preimage, _) in payments.drain(..) {
1208                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1209         }
1210
1211         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1212 }
1213
1214 #[test]
1215 fn duplicate_htlc_test() {
1216         // Test that we accept duplicate payment_hash HTLCs across the network and that
1217         // claiming/failing them are all separate and don't affect each other
1218         let chanmon_cfgs = create_chanmon_cfgs(6);
1219         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1220         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1221         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1222
1223         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1224         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1225         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1226         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1227         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1228         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1229
1230         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1231
1232         *nodes[0].network_payment_count.borrow_mut() -= 1;
1233         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1234
1235         *nodes[0].network_payment_count.borrow_mut() -= 1;
1236         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1237
1238         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1239         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1240         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1241 }
1242
1243 #[test]
1244 fn test_duplicate_htlc_different_direction_onchain() {
1245         // Test that ChannelMonitor doesn't generate 2 preimage txn
1246         // when we have 2 HTLCs with same preimage that go across a node
1247         // in opposite directions, even with the same payment secret.
1248         let chanmon_cfgs = create_chanmon_cfgs(2);
1249         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1250         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1251         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1252
1253         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1254
1255         // balancing
1256         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1257
1258         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1259
1260         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1261         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1262         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1263
1264         // Provide preimage to node 0 by claiming payment
1265         nodes[0].node.claim_funds(payment_preimage);
1266         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1267         check_added_monitors!(nodes[0], 1);
1268
1269         // Broadcast node 1 commitment txn
1270         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1271
1272         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1273         let mut has_both_htlcs = 0; // check htlcs match ones committed
1274         for outp in remote_txn[0].output.iter() {
1275                 if outp.value == 800_000 / 1000 {
1276                         has_both_htlcs += 1;
1277                 } else if outp.value == 900_000 / 1000 {
1278                         has_both_htlcs += 1;
1279                 }
1280         }
1281         assert_eq!(has_both_htlcs, 2);
1282
1283         mine_transaction(&nodes[0], &remote_txn[0]);
1284         check_added_monitors!(nodes[0], 1);
1285         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1286         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1287
1288         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1289         assert_eq!(claim_txn.len(), 8);
1290
1291         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1292
1293         check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1294         check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1295
1296         let bump_tx = if claim_txn[1] == claim_txn[4] {
1297                 assert_eq!(claim_txn[1], claim_txn[4]);
1298                 assert_eq!(claim_txn[2], claim_txn[5]);
1299
1300                 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1301
1302                 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1303                 &claim_txn[3]
1304         } else {
1305                 assert_eq!(claim_txn[1], claim_txn[3]);
1306                 assert_eq!(claim_txn[2], claim_txn[4]);
1307
1308                 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1309
1310                 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1311
1312                 &claim_txn[7]
1313         };
1314
1315         assert_eq!(claim_txn[0].input.len(), 1);
1316         assert_eq!(bump_tx.input.len(), 1);
1317         assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1318
1319         assert_eq!(claim_txn[0].input.len(), 1);
1320         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1321         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1322
1323         assert_eq!(claim_txn[6].input.len(), 1);
1324         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1325         check_spends!(claim_txn[6], remote_txn[0]);
1326         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1327
1328         let events = nodes[0].node.get_and_clear_pending_msg_events();
1329         assert_eq!(events.len(), 3);
1330         for e in events {
1331                 match e {
1332                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1333                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1334                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1335                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1336                         },
1337                         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, .. } } => {
1338                                 assert!(update_add_htlcs.is_empty());
1339                                 assert!(update_fail_htlcs.is_empty());
1340                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1341                                 assert!(update_fail_malformed_htlcs.is_empty());
1342                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1343                         },
1344                         _ => panic!("Unexpected event"),
1345                 }
1346         }
1347 }
1348
1349 #[test]
1350 fn test_basic_channel_reserve() {
1351         let chanmon_cfgs = create_chanmon_cfgs(2);
1352         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1353         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1354         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1355         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1356
1357         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1358         let channel_reserve = chan_stat.channel_reserve_msat;
1359
1360         // The 2* and +1 are for the fee spike reserve.
1361         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1362         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1363         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1364         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1365         match err {
1366                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1367                         match &fails[0] {
1368                                 &APIError::ChannelUnavailable{ref err} =>
1369                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1370                                 _ => panic!("Unexpected error variant"),
1371                         }
1372                 },
1373                 _ => panic!("Unexpected error variant"),
1374         }
1375         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1376         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);
1377
1378         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1379 }
1380
1381 #[test]
1382 fn test_fee_spike_violation_fails_htlc() {
1383         let chanmon_cfgs = create_chanmon_cfgs(2);
1384         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1385         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1386         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1387         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1388
1389         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1390         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1391         let secp_ctx = Secp256k1::new();
1392         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1393
1394         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1395
1396         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1397         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1398         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1399         let msg = msgs::UpdateAddHTLC {
1400                 channel_id: chan.2,
1401                 htlc_id: 0,
1402                 amount_msat: htlc_msat,
1403                 payment_hash: payment_hash,
1404                 cltv_expiry: htlc_cltv,
1405                 onion_routing_packet: onion_packet,
1406         };
1407
1408         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1409
1410         // Now manually create the commitment_signed message corresponding to the update_add
1411         // nodes[0] just sent. In the code for construction of this message, "local" refers
1412         // to the sender of the message, and "remote" refers to the receiver.
1413
1414         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1415
1416         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1417
1418         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1419         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1420         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1421                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1422                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1423                 let chan_signer = local_chan.get_signer();
1424                 // Make the signer believe we validated another commitment, so we can release the secret
1425                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1426
1427                 let pubkeys = chan_signer.pubkeys();
1428                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1429                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1430                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1431                  chan_signer.pubkeys().funding_pubkey)
1432         };
1433         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1434                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1435                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1436                 let chan_signer = remote_chan.get_signer();
1437                 let pubkeys = chan_signer.pubkeys();
1438                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1439                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1440                  chan_signer.pubkeys().funding_pubkey)
1441         };
1442
1443         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1444         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1445                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1446
1447         // Build the remote commitment transaction so we can sign it, and then later use the
1448         // signature for the commitment_signed message.
1449         let local_chan_balance = 1313;
1450
1451         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1452                 offered: false,
1453                 amount_msat: 3460001,
1454                 cltv_expiry: htlc_cltv,
1455                 payment_hash,
1456                 transaction_output_index: Some(1),
1457         };
1458
1459         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1460
1461         let res = {
1462                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1463                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1464                 let local_chan_signer = local_chan.get_signer();
1465                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1466                         commitment_number,
1467                         95000,
1468                         local_chan_balance,
1469                         local_chan.opt_anchors(), local_funding, remote_funding,
1470                         commit_tx_keys.clone(),
1471                         feerate_per_kw,
1472                         &mut vec![(accepted_htlc_info, ())],
1473                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1474                 );
1475                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1476         };
1477
1478         let commit_signed_msg = msgs::CommitmentSigned {
1479                 channel_id: chan.2,
1480                 signature: res.0,
1481                 htlc_signatures: res.1
1482         };
1483
1484         // Send the commitment_signed message to the nodes[1].
1485         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1486         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1487
1488         // Send the RAA to nodes[1].
1489         let raa_msg = msgs::RevokeAndACK {
1490                 channel_id: chan.2,
1491                 per_commitment_secret: local_secret,
1492                 next_per_commitment_point: next_local_point
1493         };
1494         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1495
1496         let events = nodes[1].node.get_and_clear_pending_msg_events();
1497         assert_eq!(events.len(), 1);
1498         // Make sure the HTLC failed in the way we expect.
1499         match events[0] {
1500                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1501                         assert_eq!(update_fail_htlcs.len(), 1);
1502                         update_fail_htlcs[0].clone()
1503                 },
1504                 _ => panic!("Unexpected event"),
1505         };
1506         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1507                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1508
1509         check_added_monitors!(nodes[1], 2);
1510 }
1511
1512 #[test]
1513 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1514         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1515         // Set the fee rate for the channel very high, to the point where the fundee
1516         // sending any above-dust amount would result in a channel reserve violation.
1517         // In this test we check that we would be prevented from sending an HTLC in
1518         // this situation.
1519         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1520         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1521         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1522         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1523
1524         let opt_anchors = false;
1525
1526         let mut push_amt = 100_000_000;
1527         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1528         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1529
1530         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1531
1532         // Sending exactly enough to hit the reserve amount should be accepted
1533         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1534                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1535         }
1536
1537         // However one more HTLC should be significantly over the reserve amount and fail.
1538         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1539         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1540                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1541         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1542         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);
1543 }
1544
1545 #[test]
1546 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1547         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1548         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1549         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1550         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1551         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1552
1553         let opt_anchors = false;
1554
1555         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1556         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1557         // transaction fee with 0 HTLCs (183 sats)).
1558         let mut push_amt = 100_000_000;
1559         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1560         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1561         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1562
1563         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1564         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1565                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1566         }
1567
1568         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1569         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1570         let secp_ctx = Secp256k1::new();
1571         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1572         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1573         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1574         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1575         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1576         let msg = msgs::UpdateAddHTLC {
1577                 channel_id: chan.2,
1578                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1579                 amount_msat: htlc_msat,
1580                 payment_hash: payment_hash,
1581                 cltv_expiry: htlc_cltv,
1582                 onion_routing_packet: onion_packet,
1583         };
1584
1585         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1586         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1587         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);
1588         assert_eq!(nodes[0].node.list_channels().len(), 0);
1589         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1590         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1591         check_added_monitors!(nodes[0], 1);
1592         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() });
1593 }
1594
1595 #[test]
1596 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1597         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1598         // calculating our commitment transaction fee (this was previously broken).
1599         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1600         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1601
1602         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1603         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1604         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1605
1606         let opt_anchors = false;
1607
1608         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1609         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1610         // transaction fee with 0 HTLCs (183 sats)).
1611         let mut push_amt = 100_000_000;
1612         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1613         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1614         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1615
1616         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1617                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1618         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1619         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1620         // commitment transaction fee.
1621         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1622
1623         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1624         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1625                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1626         }
1627
1628         // One more than the dust amt should fail, however.
1629         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1630         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1631                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1632 }
1633
1634 #[test]
1635 fn test_chan_init_feerate_unaffordability() {
1636         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1637         // channel reserve and feerate requirements.
1638         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1639         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1640         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1641         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1642         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1643
1644         let opt_anchors = false;
1645
1646         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1647         // HTLC.
1648         let mut push_amt = 100_000_000;
1649         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1650         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1651                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1652
1653         // During open, we don't have a "counterparty channel reserve" to check against, so that
1654         // requirement only comes into play on the open_channel handling side.
1655         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1656         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1657         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1658         open_channel_msg.push_msat += 1;
1659         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1660
1661         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1662         assert_eq!(msg_events.len(), 1);
1663         match msg_events[0] {
1664                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1665                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1666                 },
1667                 _ => panic!("Unexpected event"),
1668         }
1669 }
1670
1671 #[test]
1672 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1673         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1674         // calculating our counterparty's commitment transaction fee (this was previously broken).
1675         let chanmon_cfgs = create_chanmon_cfgs(2);
1676         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1677         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1678         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1679         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1680
1681         let payment_amt = 46000; // Dust amount
1682         // In the previous code, these first four payments would succeed.
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         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687
1688         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
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         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1694
1695         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1696         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1697         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1698         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1699 }
1700
1701 #[test]
1702 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1703         let chanmon_cfgs = create_chanmon_cfgs(3);
1704         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1705         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1706         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1707         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1708         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1709
1710         let feemsat = 239;
1711         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1712         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1713         let feerate = get_feerate!(nodes[0], chan.2);
1714         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1715
1716         // Add a 2* and +1 for the fee spike reserve.
1717         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1718         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;
1719         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1720
1721         // Add a pending HTLC.
1722         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1723         let payment_event_1 = {
1724                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1725                 check_added_monitors!(nodes[0], 1);
1726
1727                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1728                 assert_eq!(events.len(), 1);
1729                 SendEvent::from_event(events.remove(0))
1730         };
1731         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1732
1733         // Attempt to trigger a channel reserve violation --> payment failure.
1734         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1735         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;
1736         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1737         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1738
1739         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1740         let secp_ctx = Secp256k1::new();
1741         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1742         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1743         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1744         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1745         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1746         let msg = msgs::UpdateAddHTLC {
1747                 channel_id: chan.2,
1748                 htlc_id: 1,
1749                 amount_msat: htlc_msat + 1,
1750                 payment_hash: our_payment_hash_1,
1751                 cltv_expiry: htlc_cltv,
1752                 onion_routing_packet: onion_packet,
1753         };
1754
1755         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1756         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1757         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1758         assert_eq!(nodes[1].node.list_channels().len(), 1);
1759         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1760         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1761         check_added_monitors!(nodes[1], 1);
1762         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1763 }
1764
1765 #[test]
1766 fn test_inbound_outbound_capacity_is_not_zero() {
1767         let chanmon_cfgs = create_chanmon_cfgs(2);
1768         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1769         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1770         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1771         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1772         let channels0 = node_chanmgrs[0].list_channels();
1773         let channels1 = node_chanmgrs[1].list_channels();
1774         assert_eq!(channels0.len(), 1);
1775         assert_eq!(channels1.len(), 1);
1776
1777         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1778         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1779         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1780
1781         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1782         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1783 }
1784
1785 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1786         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1787 }
1788
1789 #[test]
1790 fn test_channel_reserve_holding_cell_htlcs() {
1791         let chanmon_cfgs = create_chanmon_cfgs(3);
1792         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1793         // When this test was written, the default base fee floated based on the HTLC count.
1794         // It is now fixed, so we simply set the fee to the expected value here.
1795         let mut config = test_default_channel_config();
1796         config.channel_config.forwarding_fee_base_msat = 239;
1797         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1798         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1799         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1800         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1801
1802         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1803         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1804
1805         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1806         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1807
1808         macro_rules! expect_forward {
1809                 ($node: expr) => {{
1810                         let mut events = $node.node.get_and_clear_pending_msg_events();
1811                         assert_eq!(events.len(), 1);
1812                         check_added_monitors!($node, 1);
1813                         let payment_event = SendEvent::from_event(events.remove(0));
1814                         payment_event
1815                 }}
1816         }
1817
1818         let feemsat = 239; // set above
1819         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1820         let feerate = get_feerate!(nodes[0], chan_1.2);
1821         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1822
1823         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1824
1825         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1826         {
1827                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1828                         .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1829                 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);
1830                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1831                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1832
1833                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1834                         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)));
1835                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1836                 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);
1837         }
1838
1839         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1840         // nodes[0]'s wealth
1841         loop {
1842                 let amt_msat = recv_value_0 + total_fee_msat;
1843                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1844                 // Also, ensure that each payment has enough to be over the dust limit to
1845                 // ensure it'll be included in each commit tx fee calculation.
1846                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1847                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1848                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1849                         break;
1850                 }
1851
1852                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1853                         .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1854                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1855                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1856                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1857
1858                 let (stat01_, stat11_, stat12_, stat22_) = (
1859                         get_channel_value_stat!(nodes[0], chan_1.2),
1860                         get_channel_value_stat!(nodes[1], chan_1.2),
1861                         get_channel_value_stat!(nodes[1], chan_2.2),
1862                         get_channel_value_stat!(nodes[2], chan_2.2),
1863                 );
1864
1865                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1866                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1867                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1868                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1869                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1870         }
1871
1872         // adding pending output.
1873         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1874         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1875         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1876         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1877         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1878         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1879         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1880         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1881         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1882         // policy.
1883         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1884         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1885         let amt_msat_1 = recv_value_1 + total_fee_msat;
1886
1887         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);
1888         let payment_event_1 = {
1889                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1890                 check_added_monitors!(nodes[0], 1);
1891
1892                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1893                 assert_eq!(events.len(), 1);
1894                 SendEvent::from_event(events.remove(0))
1895         };
1896         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1897
1898         // channel reserve test with htlc pending output > 0
1899         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1900         {
1901                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1902                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1903                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1904                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1905         }
1906
1907         // split the rest to test holding cell
1908         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1909         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1910         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1911         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1912         {
1913                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1914                 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);
1915         }
1916
1917         // now see if they go through on both sides
1918         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);
1919         // but this will stuck in the holding cell
1920         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1921         check_added_monitors!(nodes[0], 0);
1922         let events = nodes[0].node.get_and_clear_pending_events();
1923         assert_eq!(events.len(), 0);
1924
1925         // test with outbound holding cell amount > 0
1926         {
1927                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1928                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1929                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1930                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1931                 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);
1932         }
1933
1934         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);
1935         // this will also stuck in the holding cell
1936         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1937         check_added_monitors!(nodes[0], 0);
1938         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1939         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1940
1941         // flush the pending htlc
1942         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1943         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1944         check_added_monitors!(nodes[1], 1);
1945
1946         // the pending htlc should be promoted to committed
1947         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1948         check_added_monitors!(nodes[0], 1);
1949         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1950
1951         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1952         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1953         // No commitment_signed so get_event_msg's assert(len == 1) passes
1954         check_added_monitors!(nodes[0], 1);
1955
1956         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1957         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1958         check_added_monitors!(nodes[1], 1);
1959
1960         expect_pending_htlcs_forwardable!(nodes[1]);
1961
1962         let ref payment_event_11 = expect_forward!(nodes[1]);
1963         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1964         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1965
1966         expect_pending_htlcs_forwardable!(nodes[2]);
1967         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1968
1969         // flush the htlcs in the holding cell
1970         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1971         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1972         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1973         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1974         expect_pending_htlcs_forwardable!(nodes[1]);
1975
1976         let ref payment_event_3 = expect_forward!(nodes[1]);
1977         assert_eq!(payment_event_3.msgs.len(), 2);
1978         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1979         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1980
1981         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1982         expect_pending_htlcs_forwardable!(nodes[2]);
1983
1984         let events = nodes[2].node.get_and_clear_pending_events();
1985         assert_eq!(events.len(), 2);
1986         match events[0] {
1987                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1988                         assert_eq!(our_payment_hash_21, *payment_hash);
1989                         assert_eq!(recv_value_21, amount_msat);
1990                         match &purpose {
1991                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1992                                         assert!(payment_preimage.is_none());
1993                                         assert_eq!(our_payment_secret_21, *payment_secret);
1994                                 },
1995                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1996                         }
1997                 },
1998                 _ => panic!("Unexpected event"),
1999         }
2000         match events[1] {
2001                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
2002                         assert_eq!(our_payment_hash_22, *payment_hash);
2003                         assert_eq!(recv_value_22, amount_msat);
2004                         match &purpose {
2005                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2006                                         assert!(payment_preimage.is_none());
2007                                         assert_eq!(our_payment_secret_22, *payment_secret);
2008                                 },
2009                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2010                         }
2011                 },
2012                 _ => panic!("Unexpected event"),
2013         }
2014
2015         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2016         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2017         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2018
2019         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2020         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2021         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2022
2023         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2024         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);
2025         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2026         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2027         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2028
2029         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2030         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2031 }
2032
2033 #[test]
2034 fn channel_reserve_in_flight_removes() {
2035         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2036         // can send to its counterparty, but due to update ordering, the other side may not yet have
2037         // considered those HTLCs fully removed.
2038         // This tests that we don't count HTLCs which will not be included in the next remote
2039         // commitment transaction towards the reserve value (as it implies no commitment transaction
2040         // will be generated which violates the remote reserve value).
2041         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2042         // To test this we:
2043         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2044         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2045         //    you only consider the value of the first HTLC, it may not),
2046         //  * start routing a third HTLC from A to B,
2047         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2048         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2049         //  * deliver the first fulfill from B
2050         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2051         //    claim,
2052         //  * deliver A's response CS and RAA.
2053         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2054         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2055         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2056         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2057         let chanmon_cfgs = create_chanmon_cfgs(2);
2058         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2059         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2060         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2061         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2062
2063         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2064         // Route the first two HTLCs.
2065         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2066         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2067         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2068
2069         // Start routing the third HTLC (this is just used to get everyone in the right state).
2070         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2071         let send_1 = {
2072                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2073                 check_added_monitors!(nodes[0], 1);
2074                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2075                 assert_eq!(events.len(), 1);
2076                 SendEvent::from_event(events.remove(0))
2077         };
2078
2079         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2080         // initial fulfill/CS.
2081         nodes[1].node.claim_funds(payment_preimage_1);
2082         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2083         check_added_monitors!(nodes[1], 1);
2084         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2085
2086         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2087         // remove the second HTLC when we send the HTLC back from B to A.
2088         nodes[1].node.claim_funds(payment_preimage_2);
2089         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2090         check_added_monitors!(nodes[1], 1);
2091         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2092
2093         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2094         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2095         check_added_monitors!(nodes[0], 1);
2096         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2097         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2098
2099         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2100         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2101         check_added_monitors!(nodes[1], 1);
2102         // B is already AwaitingRAA, so cant generate a CS here
2103         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2104
2105         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2106         check_added_monitors!(nodes[1], 1);
2107         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2108
2109         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2110         check_added_monitors!(nodes[0], 1);
2111         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2112
2113         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2114         check_added_monitors!(nodes[1], 1);
2115         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2116
2117         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2118         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2119         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2120         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2121         // on-chain as necessary).
2122         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2123         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2124         check_added_monitors!(nodes[0], 1);
2125         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2126         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2127
2128         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2129         check_added_monitors!(nodes[1], 1);
2130         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2131
2132         expect_pending_htlcs_forwardable!(nodes[1]);
2133         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2134
2135         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2136         // resolve the second HTLC from A's point of view.
2137         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2138         check_added_monitors!(nodes[0], 1);
2139         expect_payment_path_successful!(nodes[0]);
2140         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2141
2142         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2143         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2144         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2145         let send_2 = {
2146                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2147                 check_added_monitors!(nodes[1], 1);
2148                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2149                 assert_eq!(events.len(), 1);
2150                 SendEvent::from_event(events.remove(0))
2151         };
2152
2153         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2154         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2155         check_added_monitors!(nodes[0], 1);
2156         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2157
2158         // Now just resolve all the outstanding messages/HTLCs for completeness...
2159
2160         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2161         check_added_monitors!(nodes[1], 1);
2162         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2163
2164         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2165         check_added_monitors!(nodes[1], 1);
2166
2167         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2168         check_added_monitors!(nodes[0], 1);
2169         expect_payment_path_successful!(nodes[0]);
2170         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2171
2172         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2173         check_added_monitors!(nodes[1], 1);
2174         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2175
2176         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2177         check_added_monitors!(nodes[0], 1);
2178
2179         expect_pending_htlcs_forwardable!(nodes[0]);
2180         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2181
2182         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2183         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2184 }
2185
2186 #[test]
2187 fn channel_monitor_network_test() {
2188         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2189         // tests that ChannelMonitor is able to recover from various states.
2190         let chanmon_cfgs = create_chanmon_cfgs(5);
2191         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2192         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2193         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2194
2195         // Create some initial channels
2196         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2197         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2198         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2199         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2200
2201         // Make sure all nodes are at the same starting height
2202         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2203         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2204         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2205         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2206         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2207
2208         // Rebalance the network a bit by relaying one payment through all the channels...
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         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2213
2214         // Simple case with no pending HTLCs:
2215         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2216         check_added_monitors!(nodes[1], 1);
2217         check_closed_broadcast!(nodes[1], true);
2218         {
2219                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2220                 assert_eq!(node_txn.len(), 1);
2221                 mine_transaction(&nodes[0], &node_txn[0]);
2222                 check_added_monitors!(nodes[0], 1);
2223                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2224         }
2225         check_closed_broadcast!(nodes[0], true);
2226         assert_eq!(nodes[0].node.list_channels().len(), 0);
2227         assert_eq!(nodes[1].node.list_channels().len(), 1);
2228         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2229         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2230
2231         // One pending HTLC is discarded by the force-close:
2232         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2233
2234         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2235         // broadcasted until we reach the timelock time).
2236         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2237         check_closed_broadcast!(nodes[1], true);
2238         check_added_monitors!(nodes[1], 1);
2239         {
2240                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2241                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2242                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2243                 mine_transaction(&nodes[2], &node_txn[0]);
2244                 check_added_monitors!(nodes[2], 1);
2245                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2246         }
2247         check_closed_broadcast!(nodes[2], true);
2248         assert_eq!(nodes[1].node.list_channels().len(), 0);
2249         assert_eq!(nodes[2].node.list_channels().len(), 1);
2250         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2251         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2252
2253         macro_rules! claim_funds {
2254                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2255                         {
2256                                 $node.node.claim_funds($preimage);
2257                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2258                                 check_added_monitors!($node, 1);
2259
2260                                 let events = $node.node.get_and_clear_pending_msg_events();
2261                                 assert_eq!(events.len(), 1);
2262                                 match events[0] {
2263                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2264                                                 assert!(update_add_htlcs.is_empty());
2265                                                 assert!(update_fail_htlcs.is_empty());
2266                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2267                                         },
2268                                         _ => panic!("Unexpected event"),
2269                                 };
2270                         }
2271                 }
2272         }
2273
2274         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2275         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2276         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2277         check_added_monitors!(nodes[2], 1);
2278         check_closed_broadcast!(nodes[2], true);
2279         let node2_commitment_txid;
2280         {
2281                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2282                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2283                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2284                 node2_commitment_txid = node_txn[0].txid();
2285
2286                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2287                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2288                 mine_transaction(&nodes[3], &node_txn[0]);
2289                 check_added_monitors!(nodes[3], 1);
2290                 check_preimage_claim(&nodes[3], &node_txn);
2291         }
2292         check_closed_broadcast!(nodes[3], true);
2293         assert_eq!(nodes[2].node.list_channels().len(), 0);
2294         assert_eq!(nodes[3].node.list_channels().len(), 1);
2295         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2296         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2297
2298         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2299         // confusing us in the following tests.
2300         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2301
2302         // One pending HTLC to time out:
2303         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2304         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2305         // buffer space).
2306
2307         let (close_chan_update_1, close_chan_update_2) = {
2308                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2309                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2310                 assert_eq!(events.len(), 2);
2311                 let close_chan_update_1 = match events[0] {
2312                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2313                                 msg.clone()
2314                         },
2315                         _ => panic!("Unexpected event"),
2316                 };
2317                 match events[1] {
2318                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2319                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2320                         },
2321                         _ => panic!("Unexpected event"),
2322                 }
2323                 check_added_monitors!(nodes[3], 1);
2324
2325                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2326                 {
2327                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2328                         node_txn.retain(|tx| {
2329                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2330                                         false
2331                                 } else { true }
2332                         });
2333                 }
2334
2335                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2336
2337                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2338                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2339
2340                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2341                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2342                 assert_eq!(events.len(), 2);
2343                 let close_chan_update_2 = match events[0] {
2344                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2345                                 msg.clone()
2346                         },
2347                         _ => panic!("Unexpected event"),
2348                 };
2349                 match events[1] {
2350                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2351                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2352                         },
2353                         _ => panic!("Unexpected event"),
2354                 }
2355                 check_added_monitors!(nodes[4], 1);
2356                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2357
2358                 mine_transaction(&nodes[4], &node_txn[0]);
2359                 check_preimage_claim(&nodes[4], &node_txn);
2360                 (close_chan_update_1, close_chan_update_2)
2361         };
2362         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2363         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2364         assert_eq!(nodes[3].node.list_channels().len(), 0);
2365         assert_eq!(nodes[4].node.list_channels().len(), 0);
2366
2367         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2368         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2369         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2370 }
2371
2372 #[test]
2373 fn test_justice_tx() {
2374         // Test justice txn built on revoked HTLC-Success tx, against both sides
2375         let mut alice_config = UserConfig::default();
2376         alice_config.channel_handshake_config.announced_channel = true;
2377         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2378         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2379         let mut bob_config = UserConfig::default();
2380         bob_config.channel_handshake_config.announced_channel = true;
2381         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2382         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2383         let user_cfgs = [Some(alice_config), Some(bob_config)];
2384         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2385         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2386         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2387         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2388         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2389         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2390         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2391         // Create some new channels:
2392         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2393
2394         // A pending HTLC which will be revoked:
2395         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2396         // Get the will-be-revoked local txn from nodes[0]
2397         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2398         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2399         assert_eq!(revoked_local_txn[0].input.len(), 1);
2400         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2401         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2402         assert_eq!(revoked_local_txn[1].input.len(), 1);
2403         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2404         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2405         // Revoke the old state
2406         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2407
2408         {
2409                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2410                 {
2411                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2412                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2413                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2414
2415                         check_spends!(node_txn[0], revoked_local_txn[0]);
2416                         node_txn.swap_remove(0);
2417                         node_txn.truncate(1);
2418                 }
2419                 check_added_monitors!(nodes[1], 1);
2420                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2421                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2422
2423                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2424                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2425                 // Verify broadcast of revoked HTLC-timeout
2426                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2427                 check_added_monitors!(nodes[0], 1);
2428                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2429                 // Broadcast revoked HTLC-timeout on node 1
2430                 mine_transaction(&nodes[1], &node_txn[1]);
2431                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2432         }
2433         get_announce_close_broadcast_events(&nodes, 0, 1);
2434
2435         assert_eq!(nodes[0].node.list_channels().len(), 0);
2436         assert_eq!(nodes[1].node.list_channels().len(), 0);
2437
2438         // We test justice_tx build by A on B's revoked HTLC-Success tx
2439         // Create some new channels:
2440         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2441         {
2442                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2443                 node_txn.clear();
2444         }
2445
2446         // A pending HTLC which will be revoked:
2447         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2448         // Get the will-be-revoked local txn from B
2449         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2450         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2451         assert_eq!(revoked_local_txn[0].input.len(), 1);
2452         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2453         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2454         // Revoke the old state
2455         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2456         {
2457                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2458                 {
2459                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2460                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2461                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2462
2463                         check_spends!(node_txn[0], revoked_local_txn[0]);
2464                         node_txn.swap_remove(0);
2465                 }
2466                 check_added_monitors!(nodes[0], 1);
2467                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2468
2469                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2470                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2471                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2472                 check_added_monitors!(nodes[1], 1);
2473                 mine_transaction(&nodes[0], &node_txn[1]);
2474                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2475                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2476         }
2477         get_announce_close_broadcast_events(&nodes, 0, 1);
2478         assert_eq!(nodes[0].node.list_channels().len(), 0);
2479         assert_eq!(nodes[1].node.list_channels().len(), 0);
2480 }
2481
2482 #[test]
2483 fn revoked_output_claim() {
2484         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2485         // transaction is broadcast by its counterparty
2486         let chanmon_cfgs = create_chanmon_cfgs(2);
2487         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2488         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2489         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2490         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2491         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2492         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2493         assert_eq!(revoked_local_txn.len(), 1);
2494         // Only output is the full channel value back to nodes[0]:
2495         assert_eq!(revoked_local_txn[0].output.len(), 1);
2496         // Send a payment through, updating everyone's latest commitment txn
2497         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2498
2499         // Inform nodes[1] that nodes[0] broadcast a stale tx
2500         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2501         check_added_monitors!(nodes[1], 1);
2502         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2503         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2504         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2505
2506         check_spends!(node_txn[0], revoked_local_txn[0]);
2507         check_spends!(node_txn[1], chan_1.3);
2508
2509         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2510         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2511         get_announce_close_broadcast_events(&nodes, 0, 1);
2512         check_added_monitors!(nodes[0], 1);
2513         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2514 }
2515
2516 #[test]
2517 fn claim_htlc_outputs_shared_tx() {
2518         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2519         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2520         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2521         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2522         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2523         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2524
2525         // Create some new channel:
2526         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2527
2528         // Rebalance the network to generate htlc in the two directions
2529         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2530         // 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
2531         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2532         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2533
2534         // Get the will-be-revoked local txn from node[0]
2535         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2536         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2537         assert_eq!(revoked_local_txn[0].input.len(), 1);
2538         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2539         assert_eq!(revoked_local_txn[1].input.len(), 1);
2540         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2541         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2542         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2543
2544         //Revoke the old state
2545         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2546
2547         {
2548                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2549                 check_added_monitors!(nodes[0], 1);
2550                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2551                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2552                 check_added_monitors!(nodes[1], 1);
2553                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2554                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2555                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2556
2557                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2558                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2559
2560                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2561                 check_spends!(node_txn[0], revoked_local_txn[0]);
2562
2563                 let mut witness_lens = BTreeSet::new();
2564                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2565                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2566                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2567                 assert_eq!(witness_lens.len(), 3);
2568                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2569                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2570                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2571
2572                 // Next nodes[1] broadcasts its current local tx state:
2573                 assert_eq!(node_txn[1].input.len(), 1);
2574                 check_spends!(node_txn[1], chan_1.3);
2575
2576                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2577                 // ANTI_REORG_DELAY confirmations.
2578                 mine_transaction(&nodes[1], &node_txn[0]);
2579                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2580                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2581         }
2582         get_announce_close_broadcast_events(&nodes, 0, 1);
2583         assert_eq!(nodes[0].node.list_channels().len(), 0);
2584         assert_eq!(nodes[1].node.list_channels().len(), 0);
2585 }
2586
2587 #[test]
2588 fn claim_htlc_outputs_single_tx() {
2589         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2590         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2591         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2592         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2593         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2594         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2595
2596         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2597
2598         // Rebalance the network to generate htlc in the two directions
2599         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2600         // 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
2601         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2602         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2603         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2604
2605         // Get the will-be-revoked local txn from node[0]
2606         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2607
2608         //Revoke the old state
2609         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2610
2611         {
2612                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2613                 check_added_monitors!(nodes[0], 1);
2614                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2615                 check_added_monitors!(nodes[1], 1);
2616                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2617                 let mut events = nodes[0].node.get_and_clear_pending_events();
2618                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2619                 match events[1] {
2620                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2621                         _ => panic!("Unexpected event"),
2622                 }
2623
2624                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2625                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2626
2627                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2628                 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2629
2630                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2631                 assert_eq!(node_txn[0].input.len(), 1);
2632                 check_spends!(node_txn[0], chan_1.3);
2633                 assert_eq!(node_txn[1].input.len(), 1);
2634                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2635                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2636                 check_spends!(node_txn[1], node_txn[0]);
2637
2638                 // Justice transactions are indices 1-2-4
2639                 assert_eq!(node_txn[2].input.len(), 1);
2640                 assert_eq!(node_txn[3].input.len(), 1);
2641                 assert_eq!(node_txn[4].input.len(), 1);
2642
2643                 check_spends!(node_txn[2], revoked_local_txn[0]);
2644                 check_spends!(node_txn[3], revoked_local_txn[0]);
2645                 check_spends!(node_txn[4], revoked_local_txn[0]);
2646
2647                 let mut witness_lens = BTreeSet::new();
2648                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2649                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2650                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2651                 assert_eq!(witness_lens.len(), 3);
2652                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2653                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2654                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2655
2656                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2657                 // ANTI_REORG_DELAY confirmations.
2658                 mine_transaction(&nodes[1], &node_txn[2]);
2659                 mine_transaction(&nodes[1], &node_txn[3]);
2660                 mine_transaction(&nodes[1], &node_txn[4]);
2661                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2662                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2663         }
2664         get_announce_close_broadcast_events(&nodes, 0, 1);
2665         assert_eq!(nodes[0].node.list_channels().len(), 0);
2666         assert_eq!(nodes[1].node.list_channels().len(), 0);
2667 }
2668
2669 #[test]
2670 fn test_htlc_on_chain_success() {
2671         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2672         // the preimage backward accordingly. So here we test that ChannelManager is
2673         // broadcasting the right event to other nodes in payment path.
2674         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2675         // A --------------------> B ----------------------> C (preimage)
2676         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2677         // commitment transaction was broadcast.
2678         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2679         // towards B.
2680         // B should be able to claim via preimage if A then broadcasts its local tx.
2681         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2682         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2683         // PaymentSent event).
2684
2685         let chanmon_cfgs = create_chanmon_cfgs(3);
2686         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2687         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2688         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2689
2690         // Create some initial channels
2691         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2692         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2693
2694         // Ensure all nodes are at the same height
2695         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2696         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2697         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2698         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2699
2700         // Rebalance the network a bit by relaying one payment through all the channels...
2701         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2702         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2703
2704         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2705         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2706
2707         // Broadcast legit commitment tx from C on B's chain
2708         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2709         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2710         assert_eq!(commitment_tx.len(), 1);
2711         check_spends!(commitment_tx[0], chan_2.3);
2712         nodes[2].node.claim_funds(our_payment_preimage);
2713         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2714         nodes[2].node.claim_funds(our_payment_preimage_2);
2715         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2716         check_added_monitors!(nodes[2], 2);
2717         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2718         assert!(updates.update_add_htlcs.is_empty());
2719         assert!(updates.update_fail_htlcs.is_empty());
2720         assert!(updates.update_fail_malformed_htlcs.is_empty());
2721         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2722
2723         mine_transaction(&nodes[2], &commitment_tx[0]);
2724         check_closed_broadcast!(nodes[2], true);
2725         check_added_monitors!(nodes[2], 1);
2726         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2727         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)
2728         assert_eq!(node_txn.len(), 5);
2729         assert_eq!(node_txn[0], node_txn[3]);
2730         assert_eq!(node_txn[1], node_txn[4]);
2731         assert_eq!(node_txn[2], commitment_tx[0]);
2732         check_spends!(node_txn[0], commitment_tx[0]);
2733         check_spends!(node_txn[1], commitment_tx[0]);
2734         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2735         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2736         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2737         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2738         assert_eq!(node_txn[0].lock_time, 0);
2739         assert_eq!(node_txn[1].lock_time, 0);
2740
2741         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2742         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2743         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2744         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2745         {
2746                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2747                 assert_eq!(added_monitors.len(), 1);
2748                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2749                 added_monitors.clear();
2750         }
2751         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2752         assert_eq!(forwarded_events.len(), 3);
2753         match forwarded_events[0] {
2754                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2755                 _ => panic!("Unexpected event"),
2756         }
2757         let chan_id = Some(chan_1.2);
2758         match forwarded_events[1] {
2759                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2760                         assert_eq!(fee_earned_msat, Some(1000));
2761                         assert_eq!(prev_channel_id, chan_id);
2762                         assert_eq!(claim_from_onchain_tx, true);
2763                         assert_eq!(next_channel_id, Some(chan_2.2));
2764                 },
2765                 _ => panic!()
2766         }
2767         match forwarded_events[2] {
2768                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2769                         assert_eq!(fee_earned_msat, Some(1000));
2770                         assert_eq!(prev_channel_id, chan_id);
2771                         assert_eq!(claim_from_onchain_tx, true);
2772                         assert_eq!(next_channel_id, Some(chan_2.2));
2773                 },
2774                 _ => panic!()
2775         }
2776         let events = nodes[1].node.get_and_clear_pending_msg_events();
2777         {
2778                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2779                 assert_eq!(added_monitors.len(), 2);
2780                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2781                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2782                 added_monitors.clear();
2783         }
2784         assert_eq!(events.len(), 3);
2785         match events[0] {
2786                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2787                 _ => panic!("Unexpected event"),
2788         }
2789         match events[1] {
2790                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2791                 _ => panic!("Unexpected event"),
2792         }
2793
2794         match events[2] {
2795                 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, .. } } => {
2796                         assert!(update_add_htlcs.is_empty());
2797                         assert!(update_fail_htlcs.is_empty());
2798                         assert_eq!(update_fulfill_htlcs.len(), 1);
2799                         assert!(update_fail_malformed_htlcs.is_empty());
2800                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2801                 },
2802                 _ => panic!("Unexpected event"),
2803         };
2804         macro_rules! check_tx_local_broadcast {
2805                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2806                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2807                         assert_eq!(node_txn.len(), 3);
2808                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2809                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2810                         check_spends!(node_txn[1], $commitment_tx);
2811                         check_spends!(node_txn[2], $commitment_tx);
2812                         assert_ne!(node_txn[1].lock_time, 0);
2813                         assert_ne!(node_txn[2].lock_time, 0);
2814                         if $htlc_offered {
2815                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2816                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2817                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2818                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2819                         } else {
2820                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2821                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2822                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2823                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2824                         }
2825                         check_spends!(node_txn[0], $chan_tx);
2826                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2827                         node_txn.clear();
2828                 } }
2829         }
2830         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2831         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2832         // timeout-claim of the output that nodes[2] just claimed via success.
2833         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2834
2835         // Broadcast legit commitment tx from A on B's chain
2836         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2837         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2838         check_spends!(node_a_commitment_tx[0], chan_1.3);
2839         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2840         check_closed_broadcast!(nodes[1], true);
2841         check_added_monitors!(nodes[1], 1);
2842         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2843         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2844         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2845         let commitment_spend =
2846                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2847                         check_spends!(node_txn[1], commitment_tx[0]);
2848                         check_spends!(node_txn[2], commitment_tx[0]);
2849                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2850                         &node_txn[0]
2851                 } else {
2852                         check_spends!(node_txn[0], commitment_tx[0]);
2853                         check_spends!(node_txn[1], commitment_tx[0]);
2854                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2855                         &node_txn[2]
2856                 };
2857
2858         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2859         assert_eq!(commitment_spend.input.len(), 2);
2860         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2861         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2862         assert_eq!(commitment_spend.lock_time, 0);
2863         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2864         check_spends!(node_txn[3], chan_1.3);
2865         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2866         check_spends!(node_txn[4], node_txn[3]);
2867         check_spends!(node_txn[5], node_txn[3]);
2868         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2869         // we already checked the same situation with A.
2870
2871         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2872         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2873         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2874         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2875         check_closed_broadcast!(nodes[0], true);
2876         check_added_monitors!(nodes[0], 1);
2877         let events = nodes[0].node.get_and_clear_pending_events();
2878         assert_eq!(events.len(), 5);
2879         let mut first_claimed = false;
2880         for event in events {
2881                 match event {
2882                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2883                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2884                                         assert!(!first_claimed);
2885                                         first_claimed = true;
2886                                 } else {
2887                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2888                                         assert_eq!(payment_hash, payment_hash_2);
2889                                 }
2890                         },
2891                         Event::PaymentPathSuccessful { .. } => {},
2892                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2893                         _ => panic!("Unexpected event"),
2894                 }
2895         }
2896         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2897 }
2898
2899 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2900         // Test that in case of a unilateral close onchain, we detect the state of output and
2901         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2902         // broadcasting the right event to other nodes in payment path.
2903         // A ------------------> B ----------------------> C (timeout)
2904         //    B's commitment tx                 C's commitment tx
2905         //            \                                  \
2906         //         B's HTLC timeout tx               B's timeout tx
2907
2908         let chanmon_cfgs = create_chanmon_cfgs(3);
2909         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2910         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2911         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2912         *nodes[0].connect_style.borrow_mut() = connect_style;
2913         *nodes[1].connect_style.borrow_mut() = connect_style;
2914         *nodes[2].connect_style.borrow_mut() = connect_style;
2915
2916         // Create some intial channels
2917         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2918         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2919
2920         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2921         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2922         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2923
2924         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2925
2926         // Broadcast legit commitment tx from C on B's chain
2927         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2928         check_spends!(commitment_tx[0], chan_2.3);
2929         nodes[2].node.fail_htlc_backwards(&payment_hash);
2930         check_added_monitors!(nodes[2], 0);
2931         expect_pending_htlcs_forwardable!(nodes[2]);
2932         check_added_monitors!(nodes[2], 1);
2933
2934         let events = nodes[2].node.get_and_clear_pending_msg_events();
2935         assert_eq!(events.len(), 1);
2936         match events[0] {
2937                 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, .. } } => {
2938                         assert!(update_add_htlcs.is_empty());
2939                         assert!(!update_fail_htlcs.is_empty());
2940                         assert!(update_fulfill_htlcs.is_empty());
2941                         assert!(update_fail_malformed_htlcs.is_empty());
2942                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2943                 },
2944                 _ => panic!("Unexpected event"),
2945         };
2946         mine_transaction(&nodes[2], &commitment_tx[0]);
2947         check_closed_broadcast!(nodes[2], true);
2948         check_added_monitors!(nodes[2], 1);
2949         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2950         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2951         assert_eq!(node_txn.len(), 1);
2952         check_spends!(node_txn[0], chan_2.3);
2953         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2954
2955         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2956         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2957         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2958         mine_transaction(&nodes[1], &commitment_tx[0]);
2959         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2960         let timeout_tx;
2961         {
2962                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2963                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2964                 assert_eq!(node_txn[0], node_txn[3]);
2965                 assert_eq!(node_txn[1], node_txn[4]);
2966
2967                 check_spends!(node_txn[2], commitment_tx[0]);
2968                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2969
2970                 check_spends!(node_txn[0], chan_2.3);
2971                 check_spends!(node_txn[1], node_txn[0]);
2972                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2973                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2974
2975                 timeout_tx = node_txn[2].clone();
2976                 node_txn.clear();
2977         }
2978
2979         mine_transaction(&nodes[1], &timeout_tx);
2980         check_added_monitors!(nodes[1], 1);
2981         check_closed_broadcast!(nodes[1], true);
2982         {
2983                 // B will rebroadcast a fee-bumped timeout transaction here.
2984                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2985                 assert_eq!(node_txn.len(), 1);
2986                 check_spends!(node_txn[0], commitment_tx[0]);
2987         }
2988
2989         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2990         {
2991                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2992                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2993                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2994                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2995                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2996                 if node_txn.len() == 1 {
2997                         check_spends!(node_txn[0], chan_2.3);
2998                 } else {
2999                         assert_eq!(node_txn.len(), 0);
3000                 }
3001         }
3002
3003         expect_pending_htlcs_forwardable!(nodes[1]);
3004         check_added_monitors!(nodes[1], 1);
3005         let events = nodes[1].node.get_and_clear_pending_msg_events();
3006         assert_eq!(events.len(), 1);
3007         match events[0] {
3008                 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, .. } } => {
3009                         assert!(update_add_htlcs.is_empty());
3010                         assert!(!update_fail_htlcs.is_empty());
3011                         assert!(update_fulfill_htlcs.is_empty());
3012                         assert!(update_fail_malformed_htlcs.is_empty());
3013                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3014                 },
3015                 _ => panic!("Unexpected event"),
3016         };
3017
3018         // Broadcast legit commitment tx from B on A's chain
3019         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3020         check_spends!(commitment_tx[0], chan_1.3);
3021
3022         mine_transaction(&nodes[0], &commitment_tx[0]);
3023         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3024
3025         check_closed_broadcast!(nodes[0], true);
3026         check_added_monitors!(nodes[0], 1);
3027         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3028         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3029         assert_eq!(node_txn.len(), 2);
3030         check_spends!(node_txn[0], chan_1.3);
3031         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3032         check_spends!(node_txn[1], commitment_tx[0]);
3033         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3034 }
3035
3036 #[test]
3037 fn test_htlc_on_chain_timeout() {
3038         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3039         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3040         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3041 }
3042
3043 #[test]
3044 fn test_simple_commitment_revoked_fail_backward() {
3045         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3046         // and fail backward accordingly.
3047
3048         let chanmon_cfgs = create_chanmon_cfgs(3);
3049         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3050         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3051         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3052
3053         // Create some initial channels
3054         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3055         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3056
3057         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3058         // Get the will-be-revoked local txn from nodes[2]
3059         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3060         // Revoke the old state
3061         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3062
3063         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3064
3065         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3066         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3067         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3068         check_added_monitors!(nodes[1], 1);
3069         check_closed_broadcast!(nodes[1], true);
3070
3071         expect_pending_htlcs_forwardable!(nodes[1]);
3072         check_added_monitors!(nodes[1], 1);
3073         let events = nodes[1].node.get_and_clear_pending_msg_events();
3074         assert_eq!(events.len(), 1);
3075         match events[0] {
3076                 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, .. } } => {
3077                         assert!(update_add_htlcs.is_empty());
3078                         assert_eq!(update_fail_htlcs.len(), 1);
3079                         assert!(update_fulfill_htlcs.is_empty());
3080                         assert!(update_fail_malformed_htlcs.is_empty());
3081                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3082
3083                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3084                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3085                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3086                 },
3087                 _ => panic!("Unexpected event"),
3088         }
3089 }
3090
3091 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3092         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3093         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3094         // commitment transaction anymore.
3095         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3096         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3097         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3098         // technically disallowed and we should probably handle it reasonably.
3099         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3100         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3101         // transactions:
3102         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3103         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3104         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3105         //   and once they revoke the previous commitment transaction (allowing us to send a new
3106         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3107         let chanmon_cfgs = create_chanmon_cfgs(3);
3108         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3109         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3110         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3111
3112         // Create some initial channels
3113         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3114         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3115
3116         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 });
3117         // Get the will-be-revoked local txn from nodes[2]
3118         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3119         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3120         // Revoke the old state
3121         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3122
3123         let value = if use_dust {
3124                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3125                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3126                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3127         } else { 3000000 };
3128
3129         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3130         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3131         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3132
3133         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3134         expect_pending_htlcs_forwardable!(nodes[2]);
3135         check_added_monitors!(nodes[2], 1);
3136         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3137         assert!(updates.update_add_htlcs.is_empty());
3138         assert!(updates.update_fulfill_htlcs.is_empty());
3139         assert!(updates.update_fail_malformed_htlcs.is_empty());
3140         assert_eq!(updates.update_fail_htlcs.len(), 1);
3141         assert!(updates.update_fee.is_none());
3142         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3143         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3144         // Drop the last RAA from 3 -> 2
3145
3146         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3147         expect_pending_htlcs_forwardable!(nodes[2]);
3148         check_added_monitors!(nodes[2], 1);
3149         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3150         assert!(updates.update_add_htlcs.is_empty());
3151         assert!(updates.update_fulfill_htlcs.is_empty());
3152         assert!(updates.update_fail_malformed_htlcs.is_empty());
3153         assert_eq!(updates.update_fail_htlcs.len(), 1);
3154         assert!(updates.update_fee.is_none());
3155         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3156         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3157         check_added_monitors!(nodes[1], 1);
3158         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3159         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3160         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3161         check_added_monitors!(nodes[2], 1);
3162
3163         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3164         expect_pending_htlcs_forwardable!(nodes[2]);
3165         check_added_monitors!(nodes[2], 1);
3166         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3167         assert!(updates.update_add_htlcs.is_empty());
3168         assert!(updates.update_fulfill_htlcs.is_empty());
3169         assert!(updates.update_fail_malformed_htlcs.is_empty());
3170         assert_eq!(updates.update_fail_htlcs.len(), 1);
3171         assert!(updates.update_fee.is_none());
3172         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3173         // At this point first_payment_hash has dropped out of the latest two commitment
3174         // transactions that nodes[1] is tracking...
3175         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3176         check_added_monitors!(nodes[1], 1);
3177         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3178         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3179         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3180         check_added_monitors!(nodes[2], 1);
3181
3182         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3183         // on nodes[2]'s RAA.
3184         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3185         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3186         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3187         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3188         check_added_monitors!(nodes[1], 0);
3189
3190         if deliver_bs_raa {
3191                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3192                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3193                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3194                 check_added_monitors!(nodes[1], 1);
3195                 let events = nodes[1].node.get_and_clear_pending_events();
3196                 assert_eq!(events.len(), 1);
3197                 match events[0] {
3198                         Event::PendingHTLCsForwardable { .. } => { },
3199                         _ => panic!("Unexpected event"),
3200                 };
3201                 // Deliberately don't process the pending fail-back so they all fail back at once after
3202                 // block connection just like the !deliver_bs_raa case
3203         }
3204
3205         let mut failed_htlcs = HashSet::new();
3206         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3207
3208         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3209         check_added_monitors!(nodes[1], 1);
3210         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3211         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3212
3213         let events = nodes[1].node.get_and_clear_pending_events();
3214         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3215         match events[0] {
3216                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3217                 _ => panic!("Unexepected event"),
3218         }
3219         match events[1] {
3220                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3221                         assert_eq!(*payment_hash, fourth_payment_hash);
3222                 },
3223                 _ => panic!("Unexpected event"),
3224         }
3225         if !deliver_bs_raa {
3226                 match events[2] {
3227                         Event::PaymentFailed { ref payment_hash, .. } => {
3228                                 assert_eq!(*payment_hash, fourth_payment_hash);
3229                         },
3230                         _ => panic!("Unexpected event"),
3231                 }
3232                 match events[3] {
3233                         Event::PendingHTLCsForwardable { .. } => { },
3234                         _ => panic!("Unexpected event"),
3235                 };
3236         }
3237         nodes[1].node.process_pending_htlc_forwards();
3238         check_added_monitors!(nodes[1], 1);
3239
3240         let events = nodes[1].node.get_and_clear_pending_msg_events();
3241         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3242         match events[if deliver_bs_raa { 1 } else { 0 }] {
3243                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3244                 _ => panic!("Unexpected event"),
3245         }
3246         match events[if deliver_bs_raa { 2 } else { 1 }] {
3247                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3248                         assert_eq!(channel_id, chan_2.2);
3249                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3250                 },
3251                 _ => panic!("Unexpected event"),
3252         }
3253         if deliver_bs_raa {
3254                 match events[0] {
3255                         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, .. } } => {
3256                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3257                                 assert_eq!(update_add_htlcs.len(), 1);
3258                                 assert!(update_fulfill_htlcs.is_empty());
3259                                 assert!(update_fail_htlcs.is_empty());
3260                                 assert!(update_fail_malformed_htlcs.is_empty());
3261                         },
3262                         _ => panic!("Unexpected event"),
3263                 }
3264         }
3265         match events[if deliver_bs_raa { 3 } else { 2 }] {
3266                 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, .. } } => {
3267                         assert!(update_add_htlcs.is_empty());
3268                         assert_eq!(update_fail_htlcs.len(), 3);
3269                         assert!(update_fulfill_htlcs.is_empty());
3270                         assert!(update_fail_malformed_htlcs.is_empty());
3271                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3272
3273                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3274                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3275                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3276
3277                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3278
3279                         let events = nodes[0].node.get_and_clear_pending_events();
3280                         assert_eq!(events.len(), 3);
3281                         match events[0] {
3282                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3283                                         assert!(failed_htlcs.insert(payment_hash.0));
3284                                         // If we delivered B's RAA we got an unknown preimage error, not something
3285                                         // that we should update our routing table for.
3286                                         if !deliver_bs_raa {
3287                                                 assert!(network_update.is_some());
3288                                         }
3289                                 },
3290                                 _ => panic!("Unexpected event"),
3291                         }
3292                         match events[1] {
3293                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3294                                         assert!(failed_htlcs.insert(payment_hash.0));
3295                                         assert!(network_update.is_some());
3296                                 },
3297                                 _ => panic!("Unexpected event"),
3298                         }
3299                         match events[2] {
3300                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3301                                         assert!(failed_htlcs.insert(payment_hash.0));
3302                                         assert!(network_update.is_some());
3303                                 },
3304                                 _ => panic!("Unexpected event"),
3305                         }
3306                 },
3307                 _ => panic!("Unexpected event"),
3308         }
3309
3310         assert!(failed_htlcs.contains(&first_payment_hash.0));
3311         assert!(failed_htlcs.contains(&second_payment_hash.0));
3312         assert!(failed_htlcs.contains(&third_payment_hash.0));
3313 }
3314
3315 #[test]
3316 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3317         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3318         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3319         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3320         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3321 }
3322
3323 #[test]
3324 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3325         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3326         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3327         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3328         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3329 }
3330
3331 #[test]
3332 fn fail_backward_pending_htlc_upon_channel_failure() {
3333         let chanmon_cfgs = create_chanmon_cfgs(2);
3334         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3335         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3336         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3337         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3338
3339         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3340         {
3341                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3342                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3343                 check_added_monitors!(nodes[0], 1);
3344
3345                 let payment_event = {
3346                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3347                         assert_eq!(events.len(), 1);
3348                         SendEvent::from_event(events.remove(0))
3349                 };
3350                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3351                 assert_eq!(payment_event.msgs.len(), 1);
3352         }
3353
3354         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3355         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3356         {
3357                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3358                 check_added_monitors!(nodes[0], 0);
3359
3360                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3361         }
3362
3363         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3364         {
3365                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3366
3367                 let secp_ctx = Secp256k1::new();
3368                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3369                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3370                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3371                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3372                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3373
3374                 // Send a 0-msat update_add_htlc to fail the channel.
3375                 let update_add_htlc = msgs::UpdateAddHTLC {
3376                         channel_id: chan.2,
3377                         htlc_id: 0,
3378                         amount_msat: 0,
3379                         payment_hash,
3380                         cltv_expiry,
3381                         onion_routing_packet,
3382                 };
3383                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3384         }
3385         let events = nodes[0].node.get_and_clear_pending_events();
3386         assert_eq!(events.len(), 2);
3387         // Check that Alice fails backward the pending HTLC from the second payment.
3388         match events[0] {
3389                 Event::PaymentPathFailed { payment_hash, .. } => {
3390                         assert_eq!(payment_hash, failed_payment_hash);
3391                 },
3392                 _ => panic!("Unexpected event"),
3393         }
3394         match events[1] {
3395                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3396                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3397                 },
3398                 _ => panic!("Unexpected event {:?}", events[1]),
3399         }
3400         check_closed_broadcast!(nodes[0], true);
3401         check_added_monitors!(nodes[0], 1);
3402 }
3403
3404 #[test]
3405 fn test_htlc_ignore_latest_remote_commitment() {
3406         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3407         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3408         let chanmon_cfgs = create_chanmon_cfgs(2);
3409         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3410         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3411         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3412         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3413
3414         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3415         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3416         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3417         check_closed_broadcast!(nodes[0], true);
3418         check_added_monitors!(nodes[0], 1);
3419         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3420
3421         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3422         assert_eq!(node_txn.len(), 3);
3423         assert_eq!(node_txn[0], node_txn[1]);
3424
3425         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3426         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3427         check_closed_broadcast!(nodes[1], true);
3428         check_added_monitors!(nodes[1], 1);
3429         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3430
3431         // Duplicate the connect_block call since this may happen due to other listeners
3432         // registering new transactions
3433         header.prev_blockhash = header.block_hash();
3434         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3435 }
3436
3437 #[test]
3438 fn test_force_close_fail_back() {
3439         // Check which HTLCs are failed-backwards on channel force-closure
3440         let chanmon_cfgs = create_chanmon_cfgs(3);
3441         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3442         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3443         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3444         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3445         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3446
3447         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3448
3449         let mut payment_event = {
3450                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3451                 check_added_monitors!(nodes[0], 1);
3452
3453                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3454                 assert_eq!(events.len(), 1);
3455                 SendEvent::from_event(events.remove(0))
3456         };
3457
3458         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3459         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3460
3461         expect_pending_htlcs_forwardable!(nodes[1]);
3462
3463         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3464         assert_eq!(events_2.len(), 1);
3465         payment_event = SendEvent::from_event(events_2.remove(0));
3466         assert_eq!(payment_event.msgs.len(), 1);
3467
3468         check_added_monitors!(nodes[1], 1);
3469         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3470         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3471         check_added_monitors!(nodes[2], 1);
3472         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3473
3474         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3475         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3476         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3477
3478         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3479         check_closed_broadcast!(nodes[2], true);
3480         check_added_monitors!(nodes[2], 1);
3481         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3482         let tx = {
3483                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3484                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3485                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3486                 // back to nodes[1] upon timeout otherwise.
3487                 assert_eq!(node_txn.len(), 1);
3488                 node_txn.remove(0)
3489         };
3490
3491         mine_transaction(&nodes[1], &tx);
3492
3493         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3494         check_closed_broadcast!(nodes[1], true);
3495         check_added_monitors!(nodes[1], 1);
3496         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3497
3498         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3499         {
3500                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3501                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &LowerBoundedFeeEstimator::new(node_cfgs[2].fee_estimator), &node_cfgs[2].logger);
3502         }
3503         mine_transaction(&nodes[2], &tx);
3504         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3505         assert_eq!(node_txn.len(), 1);
3506         assert_eq!(node_txn[0].input.len(), 1);
3507         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3508         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3509         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3510
3511         check_spends!(node_txn[0], tx);
3512 }
3513
3514 #[test]
3515 fn test_dup_events_on_peer_disconnect() {
3516         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3517         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3518         // as we used to generate the event immediately upon receipt of the payment preimage in the
3519         // update_fulfill_htlc message.
3520
3521         let chanmon_cfgs = create_chanmon_cfgs(2);
3522         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3523         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3524         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3525         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3526
3527         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3528
3529         nodes[1].node.claim_funds(payment_preimage);
3530         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3531         check_added_monitors!(nodes[1], 1);
3532         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3533         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3534         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3535
3536         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3537         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3538
3539         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3540         expect_payment_path_successful!(nodes[0]);
3541 }
3542
3543 #[test]
3544 fn test_peer_disconnected_before_funding_broadcasted() {
3545         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3546         // before the funding transaction has been broadcasted.
3547         let chanmon_cfgs = create_chanmon_cfgs(2);
3548         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3549         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3550         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3551
3552         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3553         // broadcasted, even though it's created by `nodes[0]`.
3554         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();
3555         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3556         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3557         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3558         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3559
3560         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3561         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3562
3563         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3564
3565         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3566         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3567
3568         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3569         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3570         // broadcasted.
3571         {
3572                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3573         }
3574
3575         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3576         // disconnected before the funding transaction was broadcasted.
3577         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3578         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3579
3580         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3581         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3582 }
3583
3584 #[test]
3585 fn test_simple_peer_disconnect() {
3586         // Test that we can reconnect when there are no lost messages
3587         let chanmon_cfgs = create_chanmon_cfgs(3);
3588         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3589         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3590         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3591         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3592         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3593
3594         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3595         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3596         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3597
3598         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3599         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3600         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3601         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3602
3603         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3604         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3605         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3606
3607         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3608         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3609         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3610         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3611
3612         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3613         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3614
3615         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3616         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3617
3618         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3619         {
3620                 let events = nodes[0].node.get_and_clear_pending_events();
3621                 assert_eq!(events.len(), 3);
3622                 match events[0] {
3623                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3624                                 assert_eq!(payment_preimage, payment_preimage_3);
3625                                 assert_eq!(payment_hash, payment_hash_3);
3626                         },
3627                         _ => panic!("Unexpected event"),
3628                 }
3629                 match events[1] {
3630                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3631                                 assert_eq!(payment_hash, payment_hash_5);
3632                                 assert!(rejected_by_dest);
3633                         },
3634                         _ => panic!("Unexpected event"),
3635                 }
3636                 match events[2] {
3637                         Event::PaymentPathSuccessful { .. } => {},
3638                         _ => panic!("Unexpected event"),
3639                 }
3640         }
3641
3642         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3643         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3644 }
3645
3646 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3647         // Test that we can reconnect when in-flight HTLC updates get dropped
3648         let chanmon_cfgs = create_chanmon_cfgs(2);
3649         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3650         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3651         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3652
3653         let mut as_channel_ready = None;
3654         if messages_delivered == 0 {
3655                 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3656                 as_channel_ready = Some(channel_ready);
3657                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3658                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3659                 // it before the channel_reestablish message.
3660         } else {
3661                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3662         }
3663
3664         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3665
3666         let payment_event = {
3667                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3668                 check_added_monitors!(nodes[0], 1);
3669
3670                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3671                 assert_eq!(events.len(), 1);
3672                 SendEvent::from_event(events.remove(0))
3673         };
3674         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3675
3676         if messages_delivered < 2 {
3677                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3678         } else {
3679                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3680                 if messages_delivered >= 3 {
3681                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3682                         check_added_monitors!(nodes[1], 1);
3683                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3684
3685                         if messages_delivered >= 4 {
3686                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3687                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3688                                 check_added_monitors!(nodes[0], 1);
3689
3690                                 if messages_delivered >= 5 {
3691                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3692                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3693                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3694                                         check_added_monitors!(nodes[0], 1);
3695
3696                                         if messages_delivered >= 6 {
3697                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3698                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3699                                                 check_added_monitors!(nodes[1], 1);
3700                                         }
3701                                 }
3702                         }
3703                 }
3704         }
3705
3706         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3707         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3708         if messages_delivered < 3 {
3709                 if simulate_broken_lnd {
3710                         // lnd has a long-standing bug where they send a channel_ready prior to a
3711                         // channel_reestablish if you reconnect prior to channel_ready time.
3712                         //
3713                         // Here we simulate that behavior, delivering a channel_ready immediately on
3714                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3715                         // in `reconnect_nodes` but we currently don't fail based on that.
3716                         //
3717                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3718                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3719                 }
3720                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3721                 // received on either side, both sides will need to resend them.
3722                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3723         } else if messages_delivered == 3 {
3724                 // nodes[0] still wants its RAA + commitment_signed
3725                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3726         } else if messages_delivered == 4 {
3727                 // nodes[0] still wants its commitment_signed
3728                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3729         } else if messages_delivered == 5 {
3730                 // nodes[1] still wants its final RAA
3731                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3732         } else if messages_delivered == 6 {
3733                 // Everything was delivered...
3734                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3735         }
3736
3737         let events_1 = nodes[1].node.get_and_clear_pending_events();
3738         assert_eq!(events_1.len(), 1);
3739         match events_1[0] {
3740                 Event::PendingHTLCsForwardable { .. } => { },
3741                 _ => panic!("Unexpected event"),
3742         };
3743
3744         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3745         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3746         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3747
3748         nodes[1].node.process_pending_htlc_forwards();
3749
3750         let events_2 = nodes[1].node.get_and_clear_pending_events();
3751         assert_eq!(events_2.len(), 1);
3752         match events_2[0] {
3753                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3754                         assert_eq!(payment_hash_1, *payment_hash);
3755                         assert_eq!(amount_msat, 1_000_000);
3756                         match &purpose {
3757                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3758                                         assert!(payment_preimage.is_none());
3759                                         assert_eq!(payment_secret_1, *payment_secret);
3760                                 },
3761                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3762                         }
3763                 },
3764                 _ => panic!("Unexpected event"),
3765         }
3766
3767         nodes[1].node.claim_funds(payment_preimage_1);
3768         check_added_monitors!(nodes[1], 1);
3769         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3770
3771         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3772         assert_eq!(events_3.len(), 1);
3773         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3774                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3775                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3776                         assert!(updates.update_add_htlcs.is_empty());
3777                         assert!(updates.update_fail_htlcs.is_empty());
3778                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3779                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3780                         assert!(updates.update_fee.is_none());
3781                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3782                 },
3783                 _ => panic!("Unexpected event"),
3784         };
3785
3786         if messages_delivered >= 1 {
3787                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3788
3789                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3790                 assert_eq!(events_4.len(), 1);
3791                 match events_4[0] {
3792                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3793                                 assert_eq!(payment_preimage_1, *payment_preimage);
3794                                 assert_eq!(payment_hash_1, *payment_hash);
3795                         },
3796                         _ => panic!("Unexpected event"),
3797                 }
3798
3799                 if messages_delivered >= 2 {
3800                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3801                         check_added_monitors!(nodes[0], 1);
3802                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3803
3804                         if messages_delivered >= 3 {
3805                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3806                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3807                                 check_added_monitors!(nodes[1], 1);
3808
3809                                 if messages_delivered >= 4 {
3810                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3811                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3812                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3813                                         check_added_monitors!(nodes[1], 1);
3814
3815                                         if messages_delivered >= 5 {
3816                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3817                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3818                                                 check_added_monitors!(nodes[0], 1);
3819                                         }
3820                                 }
3821                         }
3822                 }
3823         }
3824
3825         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3826         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3827         if messages_delivered < 2 {
3828                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3829                 if messages_delivered < 1 {
3830                         expect_payment_sent!(nodes[0], payment_preimage_1);
3831                 } else {
3832                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3833                 }
3834         } else if messages_delivered == 2 {
3835                 // nodes[0] still wants its RAA + commitment_signed
3836                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3837         } else if messages_delivered == 3 {
3838                 // nodes[0] still wants its commitment_signed
3839                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3840         } else if messages_delivered == 4 {
3841                 // nodes[1] still wants its final RAA
3842                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3843         } else if messages_delivered == 5 {
3844                 // Everything was delivered...
3845                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3846         }
3847
3848         if messages_delivered == 1 || messages_delivered == 2 {
3849                 expect_payment_path_successful!(nodes[0]);
3850         }
3851
3852         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3853         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3854         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3855
3856         if messages_delivered > 2 {
3857                 expect_payment_path_successful!(nodes[0]);
3858         }
3859
3860         // Channel should still work fine...
3861         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3862         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3863         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3864 }
3865
3866 #[test]
3867 fn test_drop_messages_peer_disconnect_a() {
3868         do_test_drop_messages_peer_disconnect(0, true);
3869         do_test_drop_messages_peer_disconnect(0, false);
3870         do_test_drop_messages_peer_disconnect(1, false);
3871         do_test_drop_messages_peer_disconnect(2, false);
3872 }
3873
3874 #[test]
3875 fn test_drop_messages_peer_disconnect_b() {
3876         do_test_drop_messages_peer_disconnect(3, false);
3877         do_test_drop_messages_peer_disconnect(4, false);
3878         do_test_drop_messages_peer_disconnect(5, false);
3879         do_test_drop_messages_peer_disconnect(6, false);
3880 }
3881
3882 #[test]
3883 fn test_funding_peer_disconnect() {
3884         // Test that we can lock in our funding tx while disconnected
3885         let chanmon_cfgs = create_chanmon_cfgs(2);
3886         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3887         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3888         let persister: test_utils::TestPersister;
3889         let new_chain_monitor: test_utils::TestChainMonitor;
3890         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3891         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3892         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3893
3894         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3895         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3896
3897         confirm_transaction(&nodes[0], &tx);
3898         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3899         assert!(events_1.is_empty());
3900
3901         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3902
3903         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3904         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3905
3906         confirm_transaction(&nodes[1], &tx);
3907         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3908         assert!(events_2.is_empty());
3909
3910         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3911         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3912         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3913         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3914
3915         // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3916         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3917         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3918         assert_eq!(events_3.len(), 1);
3919         let as_channel_ready = match events_3[0] {
3920                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3921                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3922                         msg.clone()
3923                 },
3924                 _ => panic!("Unexpected event {:?}", events_3[0]),
3925         };
3926
3927         // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3928         // announcement_signatures as well as channel_update.
3929         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3930         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3931         assert_eq!(events_4.len(), 3);
3932         let chan_id;
3933         let bs_channel_ready = match events_4[0] {
3934                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3935                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3936                         chan_id = msg.channel_id;
3937                         msg.clone()
3938                 },
3939                 _ => panic!("Unexpected event {:?}", events_4[0]),
3940         };
3941         let bs_announcement_sigs = match events_4[1] {
3942                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3943                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3944                         msg.clone()
3945                 },
3946                 _ => panic!("Unexpected event {:?}", events_4[1]),
3947         };
3948         match events_4[2] {
3949                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3950                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3951                 },
3952                 _ => panic!("Unexpected event {:?}", events_4[2]),
3953         }
3954
3955         // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3956         // generates a duplicative private channel_update
3957         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3958         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3959         assert_eq!(events_5.len(), 1);
3960         match events_5[0] {
3961                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3962                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3963                 },
3964                 _ => panic!("Unexpected event {:?}", events_5[0]),
3965         };
3966
3967         // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3968         // announcement_signatures.
3969         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3970         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3971         assert_eq!(events_6.len(), 1);
3972         let as_announcement_sigs = match events_6[0] {
3973                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3974                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3975                         msg.clone()
3976                 },
3977                 _ => panic!("Unexpected event {:?}", events_6[0]),
3978         };
3979
3980         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3981         // broadcast the channel announcement globally, as well as re-send its (now-public)
3982         // channel_update.
3983         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3984         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3985         assert_eq!(events_7.len(), 1);
3986         let (chan_announcement, as_update) = match events_7[0] {
3987                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3988                         (msg.clone(), update_msg.clone())
3989                 },
3990                 _ => panic!("Unexpected event {:?}", events_7[0]),
3991         };
3992
3993         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3994         // same channel_announcement.
3995         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3996         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3997         assert_eq!(events_8.len(), 1);
3998         let bs_update = match events_8[0] {
3999                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
4000                         assert_eq!(*msg, chan_announcement);
4001                         update_msg.clone()
4002                 },
4003                 _ => panic!("Unexpected event {:?}", events_8[0]),
4004         };
4005
4006         // Provide the channel announcement and public updates to the network graph
4007         nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
4008         nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
4009         nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
4010
4011         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4012         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4013         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
4014
4015         // Check that after deserialization and reconnection we can still generate an identical
4016         // channel_announcement from the cached signatures.
4017         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4018
4019         let nodes_0_serialized = nodes[0].node.encode();
4020         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4021         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4022
4023         persister = test_utils::TestPersister::new();
4024         let keys_manager = &chanmon_cfgs[0].keys_manager;
4025         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);
4026         nodes[0].chain_monitor = &new_chain_monitor;
4027         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4028         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4029                 &mut chan_0_monitor_read, keys_manager).unwrap();
4030         assert!(chan_0_monitor_read.is_empty());
4031
4032         let mut nodes_0_read = &nodes_0_serialized[..];
4033         let (_, nodes_0_deserialized_tmp) = {
4034                 let mut channel_monitors = HashMap::new();
4035                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4036                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4037                         default_config: UserConfig::default(),
4038                         keys_manager,
4039                         fee_estimator: node_cfgs[0].fee_estimator,
4040                         chain_monitor: nodes[0].chain_monitor,
4041                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4042                         logger: nodes[0].logger,
4043                         channel_monitors,
4044                 }).unwrap()
4045         };
4046         nodes_0_deserialized = nodes_0_deserialized_tmp;
4047         assert!(nodes_0_read.is_empty());
4048
4049         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4050         nodes[0].node = &nodes_0_deserialized;
4051         check_added_monitors!(nodes[0], 1);
4052
4053         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4054
4055         // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4056         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4057         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4058         let mut found_announcement = false;
4059         for event in msgs.iter() {
4060                 match event {
4061                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4062                                 if *msg == chan_announcement { found_announcement = true; }
4063                         },
4064                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4065                         _ => panic!("Unexpected event"),
4066                 }
4067         }
4068         assert!(found_announcement);
4069 }
4070
4071 #[test]
4072 fn test_channel_ready_without_best_block_updated() {
4073         // Previously, if we were offline when a funding transaction was locked in, and then we came
4074         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4075         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4076         // channel_ready immediately instead.
4077         let chanmon_cfgs = create_chanmon_cfgs(2);
4078         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4079         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4080         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4081         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4082
4083         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4084
4085         let conf_height = nodes[0].best_block_info().1 + 1;
4086         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4087         let block_txn = [funding_tx];
4088         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4089         let conf_block_header = nodes[0].get_block_header(conf_height);
4090         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4091
4092         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4093         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4094         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4095 }
4096
4097 #[test]
4098 fn test_drop_messages_peer_disconnect_dual_htlc() {
4099         // Test that we can handle reconnecting when both sides of a channel have pending
4100         // commitment_updates when we disconnect.
4101         let chanmon_cfgs = create_chanmon_cfgs(2);
4102         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4103         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4104         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4105         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4106
4107         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4108
4109         // Now try to send a second payment which will fail to send
4110         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4111         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4112         check_added_monitors!(nodes[0], 1);
4113
4114         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4115         assert_eq!(events_1.len(), 1);
4116         match events_1[0] {
4117                 MessageSendEvent::UpdateHTLCs { .. } => {},
4118                 _ => panic!("Unexpected event"),
4119         }
4120
4121         nodes[1].node.claim_funds(payment_preimage_1);
4122         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4123         check_added_monitors!(nodes[1], 1);
4124
4125         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4126         assert_eq!(events_2.len(), 1);
4127         match events_2[0] {
4128                 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 } } => {
4129                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4130                         assert!(update_add_htlcs.is_empty());
4131                         assert_eq!(update_fulfill_htlcs.len(), 1);
4132                         assert!(update_fail_htlcs.is_empty());
4133                         assert!(update_fail_malformed_htlcs.is_empty());
4134                         assert!(update_fee.is_none());
4135
4136                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4137                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4138                         assert_eq!(events_3.len(), 1);
4139                         match events_3[0] {
4140                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4141                                         assert_eq!(*payment_preimage, payment_preimage_1);
4142                                         assert_eq!(*payment_hash, payment_hash_1);
4143                                 },
4144                                 _ => panic!("Unexpected event"),
4145                         }
4146
4147                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4148                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4149                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4150                         check_added_monitors!(nodes[0], 1);
4151                 },
4152                 _ => panic!("Unexpected event"),
4153         }
4154
4155         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4156         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4157
4158         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4159         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4160         assert_eq!(reestablish_1.len(), 1);
4161         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4162         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4163         assert_eq!(reestablish_2.len(), 1);
4164
4165         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4166         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4167         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4168         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4169
4170         assert!(as_resp.0.is_none());
4171         assert!(bs_resp.0.is_none());
4172
4173         assert!(bs_resp.1.is_none());
4174         assert!(bs_resp.2.is_none());
4175
4176         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4177
4178         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4179         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4180         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4181         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4182         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4183         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4184         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4185         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4186         // No commitment_signed so get_event_msg's assert(len == 1) passes
4187         check_added_monitors!(nodes[1], 1);
4188
4189         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4190         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4191         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4192         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4193         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4194         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4195         assert!(bs_second_commitment_signed.update_fee.is_none());
4196         check_added_monitors!(nodes[1], 1);
4197
4198         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4199         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4200         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4201         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4202         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4203         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4204         assert!(as_commitment_signed.update_fee.is_none());
4205         check_added_monitors!(nodes[0], 1);
4206
4207         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4208         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4209         // No commitment_signed so get_event_msg's assert(len == 1) passes
4210         check_added_monitors!(nodes[0], 1);
4211
4212         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4213         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4214         // No commitment_signed so get_event_msg's assert(len == 1) passes
4215         check_added_monitors!(nodes[1], 1);
4216
4217         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4218         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4219         check_added_monitors!(nodes[1], 1);
4220
4221         expect_pending_htlcs_forwardable!(nodes[1]);
4222
4223         let events_5 = nodes[1].node.get_and_clear_pending_events();
4224         assert_eq!(events_5.len(), 1);
4225         match events_5[0] {
4226                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4227                         assert_eq!(payment_hash_2, *payment_hash);
4228                         match &purpose {
4229                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4230                                         assert!(payment_preimage.is_none());
4231                                         assert_eq!(payment_secret_2, *payment_secret);
4232                                 },
4233                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4234                         }
4235                 },
4236                 _ => panic!("Unexpected event"),
4237         }
4238
4239         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4240         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4241         check_added_monitors!(nodes[0], 1);
4242
4243         expect_payment_path_successful!(nodes[0]);
4244         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4245 }
4246
4247 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4248         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4249         // to avoid our counterparty failing the channel.
4250         let chanmon_cfgs = create_chanmon_cfgs(2);
4251         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4252         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4253         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4254
4255         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4256
4257         let our_payment_hash = if send_partial_mpp {
4258                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4259                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4260                 // indicates there are more HTLCs coming.
4261                 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.
4262                 let payment_id = PaymentId([42; 32]);
4263                 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();
4264                 check_added_monitors!(nodes[0], 1);
4265                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4266                 assert_eq!(events.len(), 1);
4267                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4268                 // hop should *not* yet generate any PaymentReceived event(s).
4269                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4270                 our_payment_hash
4271         } else {
4272                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4273         };
4274
4275         let mut block = Block {
4276                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4277                 txdata: vec![],
4278         };
4279         connect_block(&nodes[0], &block);
4280         connect_block(&nodes[1], &block);
4281         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4282         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4283                 block.header.prev_blockhash = block.block_hash();
4284                 connect_block(&nodes[0], &block);
4285                 connect_block(&nodes[1], &block);
4286         }
4287
4288         expect_pending_htlcs_forwardable!(nodes[1]);
4289
4290         check_added_monitors!(nodes[1], 1);
4291         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4292         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4293         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4294         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4295         assert!(htlc_timeout_updates.update_fee.is_none());
4296
4297         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4298         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4299         // 100_000 msat as u64, followed by the height at which we failed back above
4300         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4301         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4302         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4303 }
4304
4305 #[test]
4306 fn test_htlc_timeout() {
4307         do_test_htlc_timeout(true);
4308         do_test_htlc_timeout(false);
4309 }
4310
4311 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4312         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4313         let chanmon_cfgs = create_chanmon_cfgs(3);
4314         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4315         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4316         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4317         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4318         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4319
4320         // Make sure all nodes are at the same starting height
4321         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4322         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4323         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4324
4325         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4326         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4327         {
4328                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4329         }
4330         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4331         check_added_monitors!(nodes[1], 1);
4332
4333         // Now attempt to route a second payment, which should be placed in the holding cell
4334         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4335         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4336         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4337         if forwarded_htlc {
4338                 check_added_monitors!(nodes[0], 1);
4339                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4340                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4341                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4342                 expect_pending_htlcs_forwardable!(nodes[1]);
4343         }
4344         check_added_monitors!(nodes[1], 0);
4345
4346         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4347         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4348         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4349         connect_blocks(&nodes[1], 1);
4350
4351         if forwarded_htlc {
4352                 expect_pending_htlcs_forwardable!(nodes[1]);
4353                 check_added_monitors!(nodes[1], 1);
4354                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4355                 assert_eq!(fail_commit.len(), 1);
4356                 match fail_commit[0] {
4357                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4358                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4359                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4360                         },
4361                         _ => unreachable!(),
4362                 }
4363                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4364         } else {
4365                 let events = nodes[1].node.get_and_clear_pending_events();
4366                 assert_eq!(events.len(), 2);
4367                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4368                         assert_eq!(*payment_hash, second_payment_hash);
4369                 } else { panic!("Unexpected event"); }
4370                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4371                         assert_eq!(*payment_hash, second_payment_hash);
4372                 } else { panic!("Unexpected event"); }
4373         }
4374 }
4375
4376 #[test]
4377 fn test_holding_cell_htlc_add_timeouts() {
4378         do_test_holding_cell_htlc_add_timeouts(false);
4379         do_test_holding_cell_htlc_add_timeouts(true);
4380 }
4381
4382 #[test]
4383 fn test_no_txn_manager_serialize_deserialize() {
4384         let chanmon_cfgs = create_chanmon_cfgs(2);
4385         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4386         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4387         let logger: test_utils::TestLogger;
4388         let fee_estimator: test_utils::TestFeeEstimator;
4389         let persister: test_utils::TestPersister;
4390         let new_chain_monitor: test_utils::TestChainMonitor;
4391         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4392         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4393
4394         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4395
4396         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4397
4398         let nodes_0_serialized = nodes[0].node.encode();
4399         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4400         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4401                 .write(&mut chan_0_monitor_serialized).unwrap();
4402
4403         logger = test_utils::TestLogger::new();
4404         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4405         persister = test_utils::TestPersister::new();
4406         let keys_manager = &chanmon_cfgs[0].keys_manager;
4407         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4408         nodes[0].chain_monitor = &new_chain_monitor;
4409         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4410         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4411                 &mut chan_0_monitor_read, keys_manager).unwrap();
4412         assert!(chan_0_monitor_read.is_empty());
4413
4414         let mut nodes_0_read = &nodes_0_serialized[..];
4415         let config = UserConfig::default();
4416         let (_, nodes_0_deserialized_tmp) = {
4417                 let mut channel_monitors = HashMap::new();
4418                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4419                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4420                         default_config: config,
4421                         keys_manager,
4422                         fee_estimator: &fee_estimator,
4423                         chain_monitor: nodes[0].chain_monitor,
4424                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4425                         logger: &logger,
4426                         channel_monitors,
4427                 }).unwrap()
4428         };
4429         nodes_0_deserialized = nodes_0_deserialized_tmp;
4430         assert!(nodes_0_read.is_empty());
4431
4432         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4433         nodes[0].node = &nodes_0_deserialized;
4434         assert_eq!(nodes[0].node.list_channels().len(), 1);
4435         check_added_monitors!(nodes[0], 1);
4436
4437         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4438         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4439         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4440         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4441
4442         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4443         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4444         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4445         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4446
4447         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4448         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4449         for node in nodes.iter() {
4450                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4451                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4452                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4453         }
4454
4455         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4456 }
4457
4458 #[test]
4459 fn test_manager_serialize_deserialize_events() {
4460         // This test makes sure the events field in ChannelManager survives de/serialization
4461         let chanmon_cfgs = create_chanmon_cfgs(2);
4462         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4463         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4464         let fee_estimator: test_utils::TestFeeEstimator;
4465         let persister: test_utils::TestPersister;
4466         let logger: test_utils::TestLogger;
4467         let new_chain_monitor: test_utils::TestChainMonitor;
4468         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4469         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4470
4471         // Start creating a channel, but stop right before broadcasting the funding transaction
4472         let channel_value = 100000;
4473         let push_msat = 10001;
4474         let a_flags = InitFeatures::known();
4475         let b_flags = InitFeatures::known();
4476         let node_a = nodes.remove(0);
4477         let node_b = nodes.remove(0);
4478         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4479         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()));
4480         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()));
4481
4482         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4483
4484         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4485         check_added_monitors!(node_a, 0);
4486
4487         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()));
4488         {
4489                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4490                 assert_eq!(added_monitors.len(), 1);
4491                 assert_eq!(added_monitors[0].0, funding_output);
4492                 added_monitors.clear();
4493         }
4494
4495         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4496         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4497         {
4498                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4499                 assert_eq!(added_monitors.len(), 1);
4500                 assert_eq!(added_monitors[0].0, funding_output);
4501                 added_monitors.clear();
4502         }
4503         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4504
4505         nodes.push(node_a);
4506         nodes.push(node_b);
4507
4508         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4509         let nodes_0_serialized = nodes[0].node.encode();
4510         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4511         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4512
4513         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4514         logger = test_utils::TestLogger::new();
4515         persister = test_utils::TestPersister::new();
4516         let keys_manager = &chanmon_cfgs[0].keys_manager;
4517         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4518         nodes[0].chain_monitor = &new_chain_monitor;
4519         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4520         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4521                 &mut chan_0_monitor_read, keys_manager).unwrap();
4522         assert!(chan_0_monitor_read.is_empty());
4523
4524         let mut nodes_0_read = &nodes_0_serialized[..];
4525         let config = UserConfig::default();
4526         let (_, nodes_0_deserialized_tmp) = {
4527                 let mut channel_monitors = HashMap::new();
4528                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4529                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4530                         default_config: config,
4531                         keys_manager,
4532                         fee_estimator: &fee_estimator,
4533                         chain_monitor: nodes[0].chain_monitor,
4534                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4535                         logger: &logger,
4536                         channel_monitors,
4537                 }).unwrap()
4538         };
4539         nodes_0_deserialized = nodes_0_deserialized_tmp;
4540         assert!(nodes_0_read.is_empty());
4541
4542         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4543
4544         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4545         nodes[0].node = &nodes_0_deserialized;
4546
4547         // After deserializing, make sure the funding_transaction is still held by the channel manager
4548         let events_4 = nodes[0].node.get_and_clear_pending_events();
4549         assert_eq!(events_4.len(), 0);
4550         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4551         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4552
4553         // Make sure the channel is functioning as though the de/serialization never happened
4554         assert_eq!(nodes[0].node.list_channels().len(), 1);
4555         check_added_monitors!(nodes[0], 1);
4556
4557         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4558         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4559         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4560         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4561
4562         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4563         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4564         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4565         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4566
4567         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4568         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4569         for node in nodes.iter() {
4570                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4571                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4572                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4573         }
4574
4575         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4576 }
4577
4578 #[test]
4579 fn test_simple_manager_serialize_deserialize() {
4580         let chanmon_cfgs = create_chanmon_cfgs(2);
4581         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4582         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4583         let logger: test_utils::TestLogger;
4584         let fee_estimator: test_utils::TestFeeEstimator;
4585         let persister: test_utils::TestPersister;
4586         let new_chain_monitor: test_utils::TestChainMonitor;
4587         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4588         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4589         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4590
4591         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4592         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4593
4594         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4595
4596         let nodes_0_serialized = nodes[0].node.encode();
4597         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4598         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4599
4600         logger = test_utils::TestLogger::new();
4601         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4602         persister = test_utils::TestPersister::new();
4603         let keys_manager = &chanmon_cfgs[0].keys_manager;
4604         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4605         nodes[0].chain_monitor = &new_chain_monitor;
4606         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4607         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4608                 &mut chan_0_monitor_read, keys_manager).unwrap();
4609         assert!(chan_0_monitor_read.is_empty());
4610
4611         let mut nodes_0_read = &nodes_0_serialized[..];
4612         let (_, nodes_0_deserialized_tmp) = {
4613                 let mut channel_monitors = HashMap::new();
4614                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4615                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4616                         default_config: UserConfig::default(),
4617                         keys_manager,
4618                         fee_estimator: &fee_estimator,
4619                         chain_monitor: nodes[0].chain_monitor,
4620                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4621                         logger: &logger,
4622                         channel_monitors,
4623                 }).unwrap()
4624         };
4625         nodes_0_deserialized = nodes_0_deserialized_tmp;
4626         assert!(nodes_0_read.is_empty());
4627
4628         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4629         nodes[0].node = &nodes_0_deserialized;
4630         check_added_monitors!(nodes[0], 1);
4631
4632         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4633
4634         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4635         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4636 }
4637
4638 #[test]
4639 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4640         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4641         let chanmon_cfgs = create_chanmon_cfgs(4);
4642         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4643         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4644         let logger: test_utils::TestLogger;
4645         let fee_estimator: test_utils::TestFeeEstimator;
4646         let persister: test_utils::TestPersister;
4647         let new_chain_monitor: test_utils::TestChainMonitor;
4648         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4649         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4650         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4651         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4652         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4653
4654         let mut node_0_stale_monitors_serialized = Vec::new();
4655         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4656                 let mut writer = test_utils::TestVecWriter(Vec::new());
4657                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4658                 node_0_stale_monitors_serialized.push(writer.0);
4659         }
4660
4661         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4662
4663         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4664         let nodes_0_serialized = nodes[0].node.encode();
4665
4666         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4667         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4668         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4669         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4670
4671         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4672         // nodes[3])
4673         let mut node_0_monitors_serialized = Vec::new();
4674         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4675                 let mut writer = test_utils::TestVecWriter(Vec::new());
4676                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4677                 node_0_monitors_serialized.push(writer.0);
4678         }
4679
4680         logger = test_utils::TestLogger::new();
4681         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4682         persister = test_utils::TestPersister::new();
4683         let keys_manager = &chanmon_cfgs[0].keys_manager;
4684         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4685         nodes[0].chain_monitor = &new_chain_monitor;
4686
4687
4688         let mut node_0_stale_monitors = Vec::new();
4689         for serialized in node_0_stale_monitors_serialized.iter() {
4690                 let mut read = &serialized[..];
4691                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4692                 assert!(read.is_empty());
4693                 node_0_stale_monitors.push(monitor);
4694         }
4695
4696         let mut node_0_monitors = Vec::new();
4697         for serialized in node_0_monitors_serialized.iter() {
4698                 let mut read = &serialized[..];
4699                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4700                 assert!(read.is_empty());
4701                 node_0_monitors.push(monitor);
4702         }
4703
4704         let mut nodes_0_read = &nodes_0_serialized[..];
4705         if let Err(msgs::DecodeError::InvalidValue) =
4706                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4707                 default_config: UserConfig::default(),
4708                 keys_manager,
4709                 fee_estimator: &fee_estimator,
4710                 chain_monitor: nodes[0].chain_monitor,
4711                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4712                 logger: &logger,
4713                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4714         }) { } else {
4715                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4716         };
4717
4718         let mut nodes_0_read = &nodes_0_serialized[..];
4719         let (_, nodes_0_deserialized_tmp) =
4720                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4721                 default_config: UserConfig::default(),
4722                 keys_manager,
4723                 fee_estimator: &fee_estimator,
4724                 chain_monitor: nodes[0].chain_monitor,
4725                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4726                 logger: &logger,
4727                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4728         }).unwrap();
4729         nodes_0_deserialized = nodes_0_deserialized_tmp;
4730         assert!(nodes_0_read.is_empty());
4731
4732         { // Channel close should result in a commitment tx
4733                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4734                 assert_eq!(txn.len(), 1);
4735                 check_spends!(txn[0], funding_tx);
4736                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4737         }
4738
4739         for monitor in node_0_monitors.drain(..) {
4740                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4741                 check_added_monitors!(nodes[0], 1);
4742         }
4743         nodes[0].node = &nodes_0_deserialized;
4744         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4745
4746         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4747         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4748         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4749         //... and we can even still claim the payment!
4750         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4751
4752         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4753         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4754         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4755         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4756         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4757         assert_eq!(msg_events.len(), 1);
4758         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4759                 match action {
4760                         &ErrorAction::SendErrorMessage { ref msg } => {
4761                                 assert_eq!(msg.channel_id, channel_id);
4762                         },
4763                         _ => panic!("Unexpected event!"),
4764                 }
4765         }
4766 }
4767
4768 macro_rules! check_spendable_outputs {
4769         ($node: expr, $keysinterface: expr) => {
4770                 {
4771                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4772                         let mut txn = Vec::new();
4773                         let mut all_outputs = Vec::new();
4774                         let secp_ctx = Secp256k1::new();
4775                         for event in events.drain(..) {
4776                                 match event {
4777                                         Event::SpendableOutputs { mut outputs } => {
4778                                                 for outp in outputs.drain(..) {
4779                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4780                                                         all_outputs.push(outp);
4781                                                 }
4782                                         },
4783                                         _ => panic!("Unexpected event"),
4784                                 };
4785                         }
4786                         if all_outputs.len() > 1 {
4787                                 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) {
4788                                         txn.push(tx);
4789                                 }
4790                         }
4791                         txn
4792                 }
4793         }
4794 }
4795
4796 #[test]
4797 fn test_claim_sizeable_push_msat() {
4798         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4799         let chanmon_cfgs = create_chanmon_cfgs(2);
4800         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4801         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4802         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4803
4804         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4805         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4806         check_closed_broadcast!(nodes[1], true);
4807         check_added_monitors!(nodes[1], 1);
4808         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4809         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4810         assert_eq!(node_txn.len(), 1);
4811         check_spends!(node_txn[0], chan.3);
4812         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
4813
4814         mine_transaction(&nodes[1], &node_txn[0]);
4815         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4816
4817         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4818         assert_eq!(spend_txn.len(), 1);
4819         assert_eq!(spend_txn[0].input.len(), 1);
4820         check_spends!(spend_txn[0], node_txn[0]);
4821         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4822 }
4823
4824 #[test]
4825 fn test_claim_on_remote_sizeable_push_msat() {
4826         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4827         // to_remote output is encumbered by a P2WPKH
4828         let chanmon_cfgs = create_chanmon_cfgs(2);
4829         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4830         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4831         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4832
4833         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4834         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4835         check_closed_broadcast!(nodes[0], true);
4836         check_added_monitors!(nodes[0], 1);
4837         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4838
4839         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4840         assert_eq!(node_txn.len(), 1);
4841         check_spends!(node_txn[0], chan.3);
4842         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
4843
4844         mine_transaction(&nodes[1], &node_txn[0]);
4845         check_closed_broadcast!(nodes[1], true);
4846         check_added_monitors!(nodes[1], 1);
4847         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4848         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4849
4850         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4851         assert_eq!(spend_txn.len(), 1);
4852         check_spends!(spend_txn[0], node_txn[0]);
4853 }
4854
4855 #[test]
4856 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4857         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4858         // to_remote output is encumbered by a P2WPKH
4859
4860         let chanmon_cfgs = create_chanmon_cfgs(2);
4861         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4862         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4863         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4864
4865         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4866         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4867         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4868         assert_eq!(revoked_local_txn[0].input.len(), 1);
4869         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4870
4871         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4872         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4873         check_closed_broadcast!(nodes[1], true);
4874         check_added_monitors!(nodes[1], 1);
4875         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4876
4877         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4878         mine_transaction(&nodes[1], &node_txn[0]);
4879         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4880
4881         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4882         assert_eq!(spend_txn.len(), 3);
4883         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4884         check_spends!(spend_txn[1], node_txn[0]);
4885         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4886 }
4887
4888 #[test]
4889 fn test_static_spendable_outputs_preimage_tx() {
4890         let chanmon_cfgs = create_chanmon_cfgs(2);
4891         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4892         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4893         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4894
4895         // Create some initial channels
4896         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4897
4898         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4899
4900         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4901         assert_eq!(commitment_tx[0].input.len(), 1);
4902         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4903
4904         // Settle A's commitment tx on B's chain
4905         nodes[1].node.claim_funds(payment_preimage);
4906         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4907         check_added_monitors!(nodes[1], 1);
4908         mine_transaction(&nodes[1], &commitment_tx[0]);
4909         check_added_monitors!(nodes[1], 1);
4910         let events = nodes[1].node.get_and_clear_pending_msg_events();
4911         match events[0] {
4912                 MessageSendEvent::UpdateHTLCs { .. } => {},
4913                 _ => panic!("Unexpected event"),
4914         }
4915         match events[1] {
4916                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4917                 _ => panic!("Unexepected event"),
4918         }
4919
4920         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4921         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4922         assert_eq!(node_txn.len(), 3);
4923         check_spends!(node_txn[0], commitment_tx[0]);
4924         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4925         check_spends!(node_txn[1], chan_1.3);
4926         check_spends!(node_txn[2], node_txn[1]);
4927
4928         mine_transaction(&nodes[1], &node_txn[0]);
4929         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4930         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4931
4932         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4933         assert_eq!(spend_txn.len(), 1);
4934         check_spends!(spend_txn[0], node_txn[0]);
4935 }
4936
4937 #[test]
4938 fn test_static_spendable_outputs_timeout_tx() {
4939         let chanmon_cfgs = create_chanmon_cfgs(2);
4940         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4941         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4942         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4943
4944         // Create some initial channels
4945         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4946
4947         // Rebalance the network a bit by relaying one payment through all the channels ...
4948         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4949
4950         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4951
4952         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4953         assert_eq!(commitment_tx[0].input.len(), 1);
4954         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4955
4956         // Settle A's commitment tx on B' chain
4957         mine_transaction(&nodes[1], &commitment_tx[0]);
4958         check_added_monitors!(nodes[1], 1);
4959         let events = nodes[1].node.get_and_clear_pending_msg_events();
4960         match events[0] {
4961                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4962                 _ => panic!("Unexpected event"),
4963         }
4964         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4965
4966         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4967         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4968         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4969         check_spends!(node_txn[0], chan_1.3.clone());
4970         check_spends!(node_txn[1],  commitment_tx[0].clone());
4971         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4972
4973         mine_transaction(&nodes[1], &node_txn[1]);
4974         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4975         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4976         expect_payment_failed!(nodes[1], our_payment_hash, true);
4977
4978         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4979         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4980         check_spends!(spend_txn[0], commitment_tx[0]);
4981         check_spends!(spend_txn[1], node_txn[1]);
4982         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4983 }
4984
4985 #[test]
4986 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4987         let chanmon_cfgs = create_chanmon_cfgs(2);
4988         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4989         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4990         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4991
4992         // Create some initial channels
4993         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4994
4995         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4996         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4997         assert_eq!(revoked_local_txn[0].input.len(), 1);
4998         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4999
5000         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5001
5002         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5003         check_closed_broadcast!(nodes[1], true);
5004         check_added_monitors!(nodes[1], 1);
5005         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5006
5007         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5008         assert_eq!(node_txn.len(), 2);
5009         assert_eq!(node_txn[0].input.len(), 2);
5010         check_spends!(node_txn[0], revoked_local_txn[0]);
5011
5012         mine_transaction(&nodes[1], &node_txn[0]);
5013         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5014
5015         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5016         assert_eq!(spend_txn.len(), 1);
5017         check_spends!(spend_txn[0], node_txn[0]);
5018 }
5019
5020 #[test]
5021 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5022         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5023         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5024         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5025         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5026         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5027
5028         // Create some initial channels
5029         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5030
5031         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5032         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5033         assert_eq!(revoked_local_txn[0].input.len(), 1);
5034         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5035
5036         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5037
5038         // A will generate HTLC-Timeout from revoked commitment tx
5039         mine_transaction(&nodes[0], &revoked_local_txn[0]);
5040         check_closed_broadcast!(nodes[0], true);
5041         check_added_monitors!(nodes[0], 1);
5042         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5043         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5044
5045         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5046         assert_eq!(revoked_htlc_txn.len(), 2);
5047         check_spends!(revoked_htlc_txn[0], chan_1.3);
5048         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5049         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5050         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5051         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5052
5053         // B will generate justice tx from A's revoked commitment/HTLC tx
5054         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5055         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5056         check_closed_broadcast!(nodes[1], true);
5057         check_added_monitors!(nodes[1], 1);
5058         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5059
5060         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5061         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5062         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5063         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5064         // transactions next...
5065         assert_eq!(node_txn[0].input.len(), 3);
5066         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5067
5068         assert_eq!(node_txn[1].input.len(), 2);
5069         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5070         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5071                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5072         } else {
5073                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5074                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5075         }
5076
5077         assert_eq!(node_txn[2].input.len(), 1);
5078         check_spends!(node_txn[2], chan_1.3);
5079
5080         mine_transaction(&nodes[1], &node_txn[1]);
5081         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5082
5083         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5084         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5085         assert_eq!(spend_txn.len(), 1);
5086         assert_eq!(spend_txn[0].input.len(), 1);
5087         check_spends!(spend_txn[0], node_txn[1]);
5088 }
5089
5090 #[test]
5091 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5092         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5093         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5094         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5095         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5096         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5097
5098         // Create some initial channels
5099         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5100
5101         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5102         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5103         assert_eq!(revoked_local_txn[0].input.len(), 1);
5104         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5105
5106         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5107         assert_eq!(revoked_local_txn[0].output.len(), 2);
5108
5109         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5110
5111         // B will generate HTLC-Success from revoked commitment tx
5112         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5113         check_closed_broadcast!(nodes[1], true);
5114         check_added_monitors!(nodes[1], 1);
5115         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5116         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5117
5118         assert_eq!(revoked_htlc_txn.len(), 2);
5119         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5120         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5121         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5122
5123         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5124         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5125         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5126
5127         // A will generate justice tx from B's revoked commitment/HTLC tx
5128         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5129         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5130         check_closed_broadcast!(nodes[0], true);
5131         check_added_monitors!(nodes[0], 1);
5132         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5133
5134         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5135         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5136
5137         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5138         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5139         // transactions next...
5140         assert_eq!(node_txn[0].input.len(), 2);
5141         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5142         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5143                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5144         } else {
5145                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5146                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5147         }
5148
5149         assert_eq!(node_txn[1].input.len(), 1);
5150         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5151
5152         check_spends!(node_txn[2], chan_1.3);
5153
5154         mine_transaction(&nodes[0], &node_txn[1]);
5155         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5156
5157         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5158         // didn't try to generate any new transactions.
5159
5160         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5161         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5162         assert_eq!(spend_txn.len(), 3);
5163         assert_eq!(spend_txn[0].input.len(), 1);
5164         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5165         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5166         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5167         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5168 }
5169
5170 #[test]
5171 fn test_onchain_to_onchain_claim() {
5172         // Test that in case of channel closure, we detect the state of output and claim HTLC
5173         // on downstream peer's remote commitment tx.
5174         // First, have C claim an HTLC against its own latest commitment transaction.
5175         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5176         // channel.
5177         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5178         // gets broadcast.
5179
5180         let chanmon_cfgs = create_chanmon_cfgs(3);
5181         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5182         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5183         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5184
5185         // Create some initial channels
5186         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5187         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5188
5189         // Ensure all nodes are at the same height
5190         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5191         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5192         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5193         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5194
5195         // Rebalance the network a bit by relaying one payment through all the channels ...
5196         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5197         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5198
5199         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5200         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5201         check_spends!(commitment_tx[0], chan_2.3);
5202         nodes[2].node.claim_funds(payment_preimage);
5203         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5204         check_added_monitors!(nodes[2], 1);
5205         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5206         assert!(updates.update_add_htlcs.is_empty());
5207         assert!(updates.update_fail_htlcs.is_empty());
5208         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5209         assert!(updates.update_fail_malformed_htlcs.is_empty());
5210
5211         mine_transaction(&nodes[2], &commitment_tx[0]);
5212         check_closed_broadcast!(nodes[2], true);
5213         check_added_monitors!(nodes[2], 1);
5214         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5215
5216         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5217         assert_eq!(c_txn.len(), 3);
5218         assert_eq!(c_txn[0], c_txn[2]);
5219         assert_eq!(commitment_tx[0], c_txn[1]);
5220         check_spends!(c_txn[1], chan_2.3);
5221         check_spends!(c_txn[2], c_txn[1]);
5222         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5223         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5224         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5225         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5226
5227         // 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
5228         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5229         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5230         check_added_monitors!(nodes[1], 1);
5231         let events = nodes[1].node.get_and_clear_pending_events();
5232         assert_eq!(events.len(), 2);
5233         match events[0] {
5234                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5235                 _ => panic!("Unexpected event"),
5236         }
5237         match events[1] {
5238                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5239                         assert_eq!(fee_earned_msat, Some(1000));
5240                         assert_eq!(prev_channel_id, Some(chan_1.2));
5241                         assert_eq!(claim_from_onchain_tx, true);
5242                         assert_eq!(next_channel_id, Some(chan_2.2));
5243                 },
5244                 _ => panic!("Unexpected event"),
5245         }
5246         {
5247                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5248                 // ChannelMonitor: claim tx
5249                 assert_eq!(b_txn.len(), 1);
5250                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5251                 b_txn.clear();
5252         }
5253         check_added_monitors!(nodes[1], 1);
5254         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5255         assert_eq!(msg_events.len(), 3);
5256         match msg_events[0] {
5257                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5258                 _ => panic!("Unexpected event"),
5259         }
5260         match msg_events[1] {
5261                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5262                 _ => panic!("Unexpected event"),
5263         }
5264         match msg_events[2] {
5265                 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, .. } } => {
5266                         assert!(update_add_htlcs.is_empty());
5267                         assert!(update_fail_htlcs.is_empty());
5268                         assert_eq!(update_fulfill_htlcs.len(), 1);
5269                         assert!(update_fail_malformed_htlcs.is_empty());
5270                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5271                 },
5272                 _ => panic!("Unexpected event"),
5273         };
5274         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5275         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5276         mine_transaction(&nodes[1], &commitment_tx[0]);
5277         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5278         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5279         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5280         assert_eq!(b_txn.len(), 3);
5281         check_spends!(b_txn[1], chan_1.3);
5282         check_spends!(b_txn[2], b_txn[1]);
5283         check_spends!(b_txn[0], commitment_tx[0]);
5284         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5285         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5286         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5287
5288         check_closed_broadcast!(nodes[1], true);
5289         check_added_monitors!(nodes[1], 1);
5290 }
5291
5292 #[test]
5293 fn test_duplicate_payment_hash_one_failure_one_success() {
5294         // Topology : A --> B --> C --> D
5295         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5296         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5297         // we forward one of the payments onwards to D.
5298         let chanmon_cfgs = create_chanmon_cfgs(4);
5299         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5300         // When this test was written, the default base fee floated based on the HTLC count.
5301         // It is now fixed, so we simply set the fee to the expected value here.
5302         let mut config = test_default_channel_config();
5303         config.channel_config.forwarding_fee_base_msat = 196;
5304         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5305                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5306         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5307
5308         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5309         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5310         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5311
5312         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5313         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5314         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5315         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5316         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5317
5318         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5319
5320         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5321         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5322         // script push size limit so that the below script length checks match
5323         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5324         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5325                 .with_features(InvoiceFeatures::known());
5326         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5327         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5328
5329         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5330         assert_eq!(commitment_txn[0].input.len(), 1);
5331         check_spends!(commitment_txn[0], chan_2.3);
5332
5333         mine_transaction(&nodes[1], &commitment_txn[0]);
5334         check_closed_broadcast!(nodes[1], true);
5335         check_added_monitors!(nodes[1], 1);
5336         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5337         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5338
5339         let htlc_timeout_tx;
5340         { // Extract one of the two HTLC-Timeout transaction
5341                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5342                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5343                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5344                 check_spends!(node_txn[0], chan_2.3);
5345
5346                 check_spends!(node_txn[1], commitment_txn[0]);
5347                 assert_eq!(node_txn[1].input.len(), 1);
5348
5349                 if node_txn.len() > 3 {
5350                         check_spends!(node_txn[2], commitment_txn[0]);
5351                         assert_eq!(node_txn[2].input.len(), 1);
5352                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5353
5354                         check_spends!(node_txn[3], commitment_txn[0]);
5355                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5356                 } else {
5357                         check_spends!(node_txn[2], commitment_txn[0]);
5358                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5359                 }
5360
5361                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5362                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5363                 if node_txn.len() > 3 {
5364                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5365                 }
5366                 htlc_timeout_tx = node_txn[1].clone();
5367         }
5368
5369         nodes[2].node.claim_funds(our_payment_preimage);
5370         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5371
5372         mine_transaction(&nodes[2], &commitment_txn[0]);
5373         check_added_monitors!(nodes[2], 2);
5374         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5375         let events = nodes[2].node.get_and_clear_pending_msg_events();
5376         match events[0] {
5377                 MessageSendEvent::UpdateHTLCs { .. } => {},
5378                 _ => panic!("Unexpected event"),
5379         }
5380         match events[1] {
5381                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5382                 _ => panic!("Unexepected event"),
5383         }
5384         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5385         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)
5386         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5387         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5388         assert_eq!(htlc_success_txn[0].input.len(), 1);
5389         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5390         assert_eq!(htlc_success_txn[1].input.len(), 1);
5391         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5392         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5393         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5394         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5395         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5396         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5397
5398         mine_transaction(&nodes[1], &htlc_timeout_tx);
5399         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5400         expect_pending_htlcs_forwardable!(nodes[1]);
5401         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5402         assert!(htlc_updates.update_add_htlcs.is_empty());
5403         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5404         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5405         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5406         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5407         check_added_monitors!(nodes[1], 1);
5408
5409         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5410         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5411         {
5412                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5413         }
5414         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5415
5416         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5417         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5418         // and nodes[2] fee) is rounded down and then claimed in full.
5419         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5420         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5421         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5422         assert!(updates.update_add_htlcs.is_empty());
5423         assert!(updates.update_fail_htlcs.is_empty());
5424         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5425         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5426         assert!(updates.update_fail_malformed_htlcs.is_empty());
5427         check_added_monitors!(nodes[1], 1);
5428
5429         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5430         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5431
5432         let events = nodes[0].node.get_and_clear_pending_events();
5433         match events[0] {
5434                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5435                         assert_eq!(*payment_preimage, our_payment_preimage);
5436                         assert_eq!(*payment_hash, duplicate_payment_hash);
5437                 }
5438                 _ => panic!("Unexpected event"),
5439         }
5440 }
5441
5442 #[test]
5443 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5444         let chanmon_cfgs = create_chanmon_cfgs(2);
5445         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5446         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5447         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5448
5449         // Create some initial channels
5450         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5451
5452         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5453         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5454         assert_eq!(local_txn.len(), 1);
5455         assert_eq!(local_txn[0].input.len(), 1);
5456         check_spends!(local_txn[0], chan_1.3);
5457
5458         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5459         nodes[1].node.claim_funds(payment_preimage);
5460         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5461         check_added_monitors!(nodes[1], 1);
5462
5463         mine_transaction(&nodes[1], &local_txn[0]);
5464         check_added_monitors!(nodes[1], 1);
5465         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5466         let events = nodes[1].node.get_and_clear_pending_msg_events();
5467         match events[0] {
5468                 MessageSendEvent::UpdateHTLCs { .. } => {},
5469                 _ => panic!("Unexpected event"),
5470         }
5471         match events[1] {
5472                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5473                 _ => panic!("Unexepected event"),
5474         }
5475         let node_tx = {
5476                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5477                 assert_eq!(node_txn.len(), 3);
5478                 assert_eq!(node_txn[0], node_txn[2]);
5479                 assert_eq!(node_txn[1], local_txn[0]);
5480                 assert_eq!(node_txn[0].input.len(), 1);
5481                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5482                 check_spends!(node_txn[0], local_txn[0]);
5483                 node_txn[0].clone()
5484         };
5485
5486         mine_transaction(&nodes[1], &node_tx);
5487         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5488
5489         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5490         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5491         assert_eq!(spend_txn.len(), 1);
5492         assert_eq!(spend_txn[0].input.len(), 1);
5493         check_spends!(spend_txn[0], node_tx);
5494         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5495 }
5496
5497 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5498         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5499         // unrevoked commitment transaction.
5500         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5501         // a remote RAA before they could be failed backwards (and combinations thereof).
5502         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5503         // use the same payment hashes.
5504         // Thus, we use a six-node network:
5505         //
5506         // A \         / E
5507         //    - C - D -
5508         // B /         \ F
5509         // And test where C fails back to A/B when D announces its latest commitment transaction
5510         let chanmon_cfgs = create_chanmon_cfgs(6);
5511         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5512         // When this test was written, the default base fee floated based on the HTLC count.
5513         // It is now fixed, so we simply set the fee to the expected value here.
5514         let mut config = test_default_channel_config();
5515         config.channel_config.forwarding_fee_base_msat = 196;
5516         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5517                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5518         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5519
5520         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5521         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5522         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5523         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5524         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5525
5526         // Rebalance and check output sanity...
5527         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5528         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5529         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5530
5531         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5532         // 0th HTLC:
5533         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
5534         // 1st HTLC:
5535         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
5536         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5537         // 2nd HTLC:
5538         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
5539         // 3rd HTLC:
5540         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
5541         // 4th HTLC:
5542         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5543         // 5th HTLC:
5544         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5545         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5546         // 6th HTLC:
5547         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());
5548         // 7th HTLC:
5549         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());
5550
5551         // 8th HTLC:
5552         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5553         // 9th HTLC:
5554         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5555         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
5556
5557         // 10th HTLC:
5558         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
5559         // 11th HTLC:
5560         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5561         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());
5562
5563         // Double-check that six of the new HTLC were added
5564         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5565         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5566         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5567         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5568
5569         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5570         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5571         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5572         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5573         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5574         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5575         check_added_monitors!(nodes[4], 0);
5576         expect_pending_htlcs_forwardable!(nodes[4]);
5577         check_added_monitors!(nodes[4], 1);
5578
5579         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5580         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5581         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5582         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5583         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5584         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5585
5586         // Fail 3rd below-dust and 7th above-dust HTLCs
5587         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5588         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5589         check_added_monitors!(nodes[5], 0);
5590         expect_pending_htlcs_forwardable!(nodes[5]);
5591         check_added_monitors!(nodes[5], 1);
5592
5593         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5594         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5595         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5596         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5597
5598         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5599
5600         expect_pending_htlcs_forwardable!(nodes[3]);
5601         check_added_monitors!(nodes[3], 1);
5602         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5603         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5604         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5605         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5606         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5607         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5608         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5609         if deliver_last_raa {
5610                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5611         } else {
5612                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5613         }
5614
5615         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5616         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5617         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5618         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5619         //
5620         // We now broadcast the latest commitment transaction, which *should* result in failures for
5621         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5622         // the non-broadcast above-dust HTLCs.
5623         //
5624         // Alternatively, we may broadcast the previous commitment transaction, which should only
5625         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5626         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5627
5628         if announce_latest {
5629                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5630         } else {
5631                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5632         }
5633         let events = nodes[2].node.get_and_clear_pending_events();
5634         let close_event = if deliver_last_raa {
5635                 assert_eq!(events.len(), 2);
5636                 events[1].clone()
5637         } else {
5638                 assert_eq!(events.len(), 1);
5639                 events[0].clone()
5640         };
5641         match close_event {
5642                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5643                 _ => panic!("Unexpected event"),
5644         }
5645
5646         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5647         check_closed_broadcast!(nodes[2], true);
5648         if deliver_last_raa {
5649                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5650         } else {
5651                 expect_pending_htlcs_forwardable!(nodes[2]);
5652         }
5653         check_added_monitors!(nodes[2], 3);
5654
5655         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5656         assert_eq!(cs_msgs.len(), 2);
5657         let mut a_done = false;
5658         for msg in cs_msgs {
5659                 match msg {
5660                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5661                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5662                                 // should be failed-backwards here.
5663                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5664                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5665                                         for htlc in &updates.update_fail_htlcs {
5666                                                 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 });
5667                                         }
5668                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5669                                         assert!(!a_done);
5670                                         a_done = true;
5671                                         &nodes[0]
5672                                 } else {
5673                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5674                                         for htlc in &updates.update_fail_htlcs {
5675                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5676                                         }
5677                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5678                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5679                                         &nodes[1]
5680                                 };
5681                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5682                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5683                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5684                                 if announce_latest {
5685                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5686                                         if *node_id == nodes[0].node.get_our_node_id() {
5687                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5688                                         }
5689                                 }
5690                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5691                         },
5692                         _ => panic!("Unexpected event"),
5693                 }
5694         }
5695
5696         let as_events = nodes[0].node.get_and_clear_pending_events();
5697         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5698         let mut as_failds = HashSet::new();
5699         let mut as_updates = 0;
5700         for event in as_events.iter() {
5701                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5702                         assert!(as_failds.insert(*payment_hash));
5703                         if *payment_hash != payment_hash_2 {
5704                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5705                         } else {
5706                                 assert!(!rejected_by_dest);
5707                         }
5708                         if network_update.is_some() {
5709                                 as_updates += 1;
5710                         }
5711                 } else { panic!("Unexpected event"); }
5712         }
5713         assert!(as_failds.contains(&payment_hash_1));
5714         assert!(as_failds.contains(&payment_hash_2));
5715         if announce_latest {
5716                 assert!(as_failds.contains(&payment_hash_3));
5717                 assert!(as_failds.contains(&payment_hash_5));
5718         }
5719         assert!(as_failds.contains(&payment_hash_6));
5720
5721         let bs_events = nodes[1].node.get_and_clear_pending_events();
5722         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5723         let mut bs_failds = HashSet::new();
5724         let mut bs_updates = 0;
5725         for event in bs_events.iter() {
5726                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5727                         assert!(bs_failds.insert(*payment_hash));
5728                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5729                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5730                         } else {
5731                                 assert!(!rejected_by_dest);
5732                         }
5733                         if network_update.is_some() {
5734                                 bs_updates += 1;
5735                         }
5736                 } else { panic!("Unexpected event"); }
5737         }
5738         assert!(bs_failds.contains(&payment_hash_1));
5739         assert!(bs_failds.contains(&payment_hash_2));
5740         if announce_latest {
5741                 assert!(bs_failds.contains(&payment_hash_4));
5742         }
5743         assert!(bs_failds.contains(&payment_hash_5));
5744
5745         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5746         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5747         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5748         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5749         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5750         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5751 }
5752
5753 #[test]
5754 fn test_fail_backwards_latest_remote_announce_a() {
5755         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5756 }
5757
5758 #[test]
5759 fn test_fail_backwards_latest_remote_announce_b() {
5760         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5761 }
5762
5763 #[test]
5764 fn test_fail_backwards_previous_remote_announce() {
5765         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5766         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5767         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5768 }
5769
5770 #[test]
5771 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5772         let chanmon_cfgs = create_chanmon_cfgs(2);
5773         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5774         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5775         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5776
5777         // Create some initial channels
5778         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5779
5780         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5781         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5782         assert_eq!(local_txn[0].input.len(), 1);
5783         check_spends!(local_txn[0], chan_1.3);
5784
5785         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5786         mine_transaction(&nodes[0], &local_txn[0]);
5787         check_closed_broadcast!(nodes[0], true);
5788         check_added_monitors!(nodes[0], 1);
5789         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5790         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5791
5792         let htlc_timeout = {
5793                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5794                 assert_eq!(node_txn.len(), 2);
5795                 check_spends!(node_txn[0], chan_1.3);
5796                 assert_eq!(node_txn[1].input.len(), 1);
5797                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5798                 check_spends!(node_txn[1], local_txn[0]);
5799                 node_txn[1].clone()
5800         };
5801
5802         mine_transaction(&nodes[0], &htlc_timeout);
5803         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5804         expect_payment_failed!(nodes[0], our_payment_hash, true);
5805
5806         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5807         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5808         assert_eq!(spend_txn.len(), 3);
5809         check_spends!(spend_txn[0], local_txn[0]);
5810         assert_eq!(spend_txn[1].input.len(), 1);
5811         check_spends!(spend_txn[1], htlc_timeout);
5812         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5813         assert_eq!(spend_txn[2].input.len(), 2);
5814         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5815         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5816                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5817 }
5818
5819 #[test]
5820 fn test_key_derivation_params() {
5821         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5822         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5823         // let us re-derive the channel key set to then derive a delayed_payment_key.
5824
5825         let chanmon_cfgs = create_chanmon_cfgs(3);
5826
5827         // We manually create the node configuration to backup the seed.
5828         let seed = [42; 32];
5829         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5830         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);
5831         let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5832         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() };
5833         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5834         node_cfgs.remove(0);
5835         node_cfgs.insert(0, node);
5836
5837         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5838         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5839
5840         // Create some initial channels
5841         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5842         // for node 0
5843         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5844         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5845         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5846
5847         // Ensure all nodes are at the same height
5848         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5849         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5850         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5851         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5852
5853         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5854         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5855         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5856         assert_eq!(local_txn_1[0].input.len(), 1);
5857         check_spends!(local_txn_1[0], chan_1.3);
5858
5859         // We check funding pubkey are unique
5860         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]));
5861         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]));
5862         if from_0_funding_key_0 == from_1_funding_key_0
5863             || from_0_funding_key_0 == from_1_funding_key_1
5864             || from_0_funding_key_1 == from_1_funding_key_0
5865             || from_0_funding_key_1 == from_1_funding_key_1 {
5866                 panic!("Funding pubkeys aren't unique");
5867         }
5868
5869         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5870         mine_transaction(&nodes[0], &local_txn_1[0]);
5871         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5872         check_closed_broadcast!(nodes[0], true);
5873         check_added_monitors!(nodes[0], 1);
5874         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5875
5876         let htlc_timeout = {
5877                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5878                 assert_eq!(node_txn[1].input.len(), 1);
5879                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5880                 check_spends!(node_txn[1], local_txn_1[0]);
5881                 node_txn[1].clone()
5882         };
5883
5884         mine_transaction(&nodes[0], &htlc_timeout);
5885         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5886         expect_payment_failed!(nodes[0], our_payment_hash, true);
5887
5888         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5889         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5890         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5891         assert_eq!(spend_txn.len(), 3);
5892         check_spends!(spend_txn[0], local_txn_1[0]);
5893         assert_eq!(spend_txn[1].input.len(), 1);
5894         check_spends!(spend_txn[1], htlc_timeout);
5895         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5896         assert_eq!(spend_txn[2].input.len(), 2);
5897         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5898         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5899                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5900 }
5901
5902 #[test]
5903 fn test_static_output_closing_tx() {
5904         let chanmon_cfgs = create_chanmon_cfgs(2);
5905         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5906         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5907         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5908
5909         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5910
5911         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5912         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5913
5914         mine_transaction(&nodes[0], &closing_tx);
5915         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5916         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5917
5918         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5919         assert_eq!(spend_txn.len(), 1);
5920         check_spends!(spend_txn[0], closing_tx);
5921
5922         mine_transaction(&nodes[1], &closing_tx);
5923         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5924         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5925
5926         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5927         assert_eq!(spend_txn.len(), 1);
5928         check_spends!(spend_txn[0], closing_tx);
5929 }
5930
5931 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5932         let chanmon_cfgs = create_chanmon_cfgs(2);
5933         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5934         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5935         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5936         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5937
5938         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5939
5940         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5941         // present in B's local commitment transaction, but none of A's commitment transactions.
5942         nodes[1].node.claim_funds(payment_preimage);
5943         check_added_monitors!(nodes[1], 1);
5944         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5945
5946         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5947         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5948         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5949
5950         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5951         check_added_monitors!(nodes[0], 1);
5952         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5953         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5954         check_added_monitors!(nodes[1], 1);
5955
5956         let starting_block = nodes[1].best_block_info();
5957         let mut block = Block {
5958                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5959                 txdata: vec![],
5960         };
5961         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5962                 connect_block(&nodes[1], &block);
5963                 block.header.prev_blockhash = block.block_hash();
5964         }
5965         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5966         check_closed_broadcast!(nodes[1], true);
5967         check_added_monitors!(nodes[1], 1);
5968         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5969 }
5970
5971 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5972         let chanmon_cfgs = create_chanmon_cfgs(2);
5973         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5974         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5975         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5976         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5977
5978         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5979         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5980         check_added_monitors!(nodes[0], 1);
5981
5982         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5983
5984         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5985         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5986         // to "time out" the HTLC.
5987
5988         let starting_block = nodes[1].best_block_info();
5989         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5990
5991         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5992                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5993                 header.prev_blockhash = header.block_hash();
5994         }
5995         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5996         check_closed_broadcast!(nodes[0], true);
5997         check_added_monitors!(nodes[0], 1);
5998         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5999 }
6000
6001 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
6002         let chanmon_cfgs = create_chanmon_cfgs(3);
6003         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6004         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6005         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6006         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6007
6008         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6009         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6010         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6011         // actually revoked.
6012         let htlc_value = if use_dust { 50000 } else { 3000000 };
6013         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6014         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6015         expect_pending_htlcs_forwardable!(nodes[1]);
6016         check_added_monitors!(nodes[1], 1);
6017
6018         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6019         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6020         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6021         check_added_monitors!(nodes[0], 1);
6022         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6023         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6024         check_added_monitors!(nodes[1], 1);
6025         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6026         check_added_monitors!(nodes[1], 1);
6027         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6028
6029         if check_revoke_no_close {
6030                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6031                 check_added_monitors!(nodes[0], 1);
6032         }
6033
6034         let starting_block = nodes[1].best_block_info();
6035         let mut block = Block {
6036                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6037                 txdata: vec![],
6038         };
6039         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6040                 connect_block(&nodes[0], &block);
6041                 block.header.prev_blockhash = block.block_hash();
6042         }
6043         if !check_revoke_no_close {
6044                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6045                 check_closed_broadcast!(nodes[0], true);
6046                 check_added_monitors!(nodes[0], 1);
6047                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6048         } else {
6049                 let events = nodes[0].node.get_and_clear_pending_events();
6050                 assert_eq!(events.len(), 2);
6051                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6052                         assert_eq!(*payment_hash, our_payment_hash);
6053                 } else { panic!("Unexpected event"); }
6054                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6055                         assert_eq!(*payment_hash, our_payment_hash);
6056                 } else { panic!("Unexpected event"); }
6057         }
6058 }
6059
6060 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6061 // There are only a few cases to test here:
6062 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
6063 //    broadcastable commitment transactions result in channel closure,
6064 //  * its included in an unrevoked-but-previous remote commitment transaction,
6065 //  * its included in the latest remote or local commitment transactions.
6066 // We test each of the three possible commitment transactions individually and use both dust and
6067 // non-dust HTLCs.
6068 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6069 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6070 // tested for at least one of the cases in other tests.
6071 #[test]
6072 fn htlc_claim_single_commitment_only_a() {
6073         do_htlc_claim_local_commitment_only(true);
6074         do_htlc_claim_local_commitment_only(false);
6075
6076         do_htlc_claim_current_remote_commitment_only(true);
6077         do_htlc_claim_current_remote_commitment_only(false);
6078 }
6079
6080 #[test]
6081 fn htlc_claim_single_commitment_only_b() {
6082         do_htlc_claim_previous_remote_commitment_only(true, false);
6083         do_htlc_claim_previous_remote_commitment_only(false, false);
6084         do_htlc_claim_previous_remote_commitment_only(true, true);
6085         do_htlc_claim_previous_remote_commitment_only(false, true);
6086 }
6087
6088 #[test]
6089 #[should_panic]
6090 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6091         let chanmon_cfgs = create_chanmon_cfgs(2);
6092         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6093         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6094         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6095         // Force duplicate randomness for every get-random call
6096         for node in nodes.iter() {
6097                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6098         }
6099
6100         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6101         let channel_value_satoshis=10000;
6102         let push_msat=10001;
6103         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6104         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6105         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6106         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6107
6108         // Create a second channel with the same random values. This used to panic due to a colliding
6109         // channel_id, but now panics due to a colliding outbound SCID alias.
6110         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6111 }
6112
6113 #[test]
6114 fn bolt2_open_channel_sending_node_checks_part2() {
6115         let chanmon_cfgs = create_chanmon_cfgs(2);
6116         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6117         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6118         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6119
6120         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6121         let channel_value_satoshis=2^24;
6122         let push_msat=10001;
6123         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6124
6125         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6126         let channel_value_satoshis=10000;
6127         // Test when push_msat is equal to 1000 * funding_satoshis.
6128         let push_msat=1000*channel_value_satoshis+1;
6129         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6130
6131         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6132         let channel_value_satoshis=10000;
6133         let push_msat=10001;
6134         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
6135         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6136         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6137
6138         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6139         // 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
6140         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6141
6142         // 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.
6143         assert!(BREAKDOWN_TIMEOUT>0);
6144         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6145
6146         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6147         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6148         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6149
6150         // 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.
6151         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6152         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6153         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6154         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6155         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6156 }
6157
6158 #[test]
6159 fn bolt2_open_channel_sane_dust_limit() {
6160         let chanmon_cfgs = create_chanmon_cfgs(2);
6161         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6162         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6163         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6164
6165         let channel_value_satoshis=1000000;
6166         let push_msat=10001;
6167         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6168         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6169         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6170         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6171
6172         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6173         let events = nodes[1].node.get_and_clear_pending_msg_events();
6174         let err_msg = match events[0] {
6175                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6176                         msg.clone()
6177                 },
6178                 _ => panic!("Unexpected event"),
6179         };
6180         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6181 }
6182
6183 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6184 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6185 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6186 // is no longer affordable once it's freed.
6187 #[test]
6188 fn test_fail_holding_cell_htlc_upon_free() {
6189         let chanmon_cfgs = create_chanmon_cfgs(2);
6190         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6191         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6192         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6193         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6194
6195         // First nodes[0] generates an update_fee, setting the channel's
6196         // pending_update_fee.
6197         {
6198                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6199                 *feerate_lock += 20;
6200         }
6201         nodes[0].node.timer_tick_occurred();
6202         check_added_monitors!(nodes[0], 1);
6203
6204         let events = nodes[0].node.get_and_clear_pending_msg_events();
6205         assert_eq!(events.len(), 1);
6206         let (update_msg, commitment_signed) = match events[0] {
6207                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6208                         (update_fee.as_ref(), commitment_signed)
6209                 },
6210                 _ => panic!("Unexpected event"),
6211         };
6212
6213         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6214
6215         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6216         let channel_reserve = chan_stat.channel_reserve_msat;
6217         let feerate = get_feerate!(nodes[0], chan.2);
6218         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6219
6220         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6221         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6222         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6223
6224         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6225         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6226         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6227         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6228
6229         // Flush the pending fee update.
6230         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6231         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6232         check_added_monitors!(nodes[1], 1);
6233         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6234         check_added_monitors!(nodes[0], 1);
6235
6236         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6237         // HTLC, but now that the fee has been raised the payment will now fail, causing
6238         // us to surface its failure to the user.
6239         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6240         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6241         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);
6242         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 {}",
6243                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6244         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6245
6246         // Check that the payment failed to be sent out.
6247         let events = nodes[0].node.get_and_clear_pending_events();
6248         assert_eq!(events.len(), 1);
6249         match &events[0] {
6250                 &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, .. } => {
6251                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6252                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6253                         assert_eq!(*rejected_by_dest, false);
6254                         assert_eq!(*all_paths_failed, true);
6255                         assert_eq!(*network_update, None);
6256                         assert_eq!(*short_channel_id, None);
6257                         assert_eq!(*error_code, None);
6258                         assert_eq!(*error_data, None);
6259                 },
6260                 _ => panic!("Unexpected event"),
6261         }
6262 }
6263
6264 // Test that if multiple HTLCs are released from the holding cell and one is
6265 // valid but the other is no longer valid upon release, the valid HTLC can be
6266 // successfully completed while the other one fails as expected.
6267 #[test]
6268 fn test_free_and_fail_holding_cell_htlcs() {
6269         let chanmon_cfgs = create_chanmon_cfgs(2);
6270         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6271         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6272         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6273         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6274
6275         // First nodes[0] generates an update_fee, setting the channel's
6276         // pending_update_fee.
6277         {
6278                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6279                 *feerate_lock += 200;
6280         }
6281         nodes[0].node.timer_tick_occurred();
6282         check_added_monitors!(nodes[0], 1);
6283
6284         let events = nodes[0].node.get_and_clear_pending_msg_events();
6285         assert_eq!(events.len(), 1);
6286         let (update_msg, commitment_signed) = match events[0] {
6287                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6288                         (update_fee.as_ref(), commitment_signed)
6289                 },
6290                 _ => panic!("Unexpected event"),
6291         };
6292
6293         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6294
6295         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6296         let channel_reserve = chan_stat.channel_reserve_msat;
6297         let feerate = get_feerate!(nodes[0], chan.2);
6298         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6299
6300         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6301         let amt_1 = 20000;
6302         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6303         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6304         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6305
6306         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6307         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6308         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6309         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6310         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6311         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6312         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6313
6314         // Flush the pending fee update.
6315         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6316         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6317         check_added_monitors!(nodes[1], 1);
6318         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6319         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6320         check_added_monitors!(nodes[0], 2);
6321
6322         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6323         // but now that the fee has been raised the second payment will now fail, causing us
6324         // to surface its failure to the user. The first payment should succeed.
6325         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6326         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6327         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);
6328         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 {}",
6329                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6330         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6331
6332         // Check that the second payment failed to be sent out.
6333         let events = nodes[0].node.get_and_clear_pending_events();
6334         assert_eq!(events.len(), 1);
6335         match &events[0] {
6336                 &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, .. } => {
6337                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6338                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6339                         assert_eq!(*rejected_by_dest, false);
6340                         assert_eq!(*all_paths_failed, true);
6341                         assert_eq!(*network_update, None);
6342                         assert_eq!(*short_channel_id, None);
6343                         assert_eq!(*error_code, None);
6344                         assert_eq!(*error_data, None);
6345                 },
6346                 _ => panic!("Unexpected event"),
6347         }
6348
6349         // Complete the first payment and the RAA from the fee update.
6350         let (payment_event, send_raa_event) = {
6351                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6352                 assert_eq!(msgs.len(), 2);
6353                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6354         };
6355         let raa = match send_raa_event {
6356                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6357                 _ => panic!("Unexpected event"),
6358         };
6359         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6360         check_added_monitors!(nodes[1], 1);
6361         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6362         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6363         let events = nodes[1].node.get_and_clear_pending_events();
6364         assert_eq!(events.len(), 1);
6365         match events[0] {
6366                 Event::PendingHTLCsForwardable { .. } => {},
6367                 _ => panic!("Unexpected event"),
6368         }
6369         nodes[1].node.process_pending_htlc_forwards();
6370         let events = nodes[1].node.get_and_clear_pending_events();
6371         assert_eq!(events.len(), 1);
6372         match events[0] {
6373                 Event::PaymentReceived { .. } => {},
6374                 _ => panic!("Unexpected event"),
6375         }
6376         nodes[1].node.claim_funds(payment_preimage_1);
6377         check_added_monitors!(nodes[1], 1);
6378         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6379
6380         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6381         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6382         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6383         expect_payment_sent!(nodes[0], payment_preimage_1);
6384 }
6385
6386 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6387 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6388 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6389 // once it's freed.
6390 #[test]
6391 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6392         let chanmon_cfgs = create_chanmon_cfgs(3);
6393         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6394         // When this test was written, the default base fee floated based on the HTLC count.
6395         // It is now fixed, so we simply set the fee to the expected value here.
6396         let mut config = test_default_channel_config();
6397         config.channel_config.forwarding_fee_base_msat = 196;
6398         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6399         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6400         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6401         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6402
6403         // First nodes[1] generates an update_fee, setting the channel's
6404         // pending_update_fee.
6405         {
6406                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6407                 *feerate_lock += 20;
6408         }
6409         nodes[1].node.timer_tick_occurred();
6410         check_added_monitors!(nodes[1], 1);
6411
6412         let events = nodes[1].node.get_and_clear_pending_msg_events();
6413         assert_eq!(events.len(), 1);
6414         let (update_msg, commitment_signed) = match events[0] {
6415                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6416                         (update_fee.as_ref(), commitment_signed)
6417                 },
6418                 _ => panic!("Unexpected event"),
6419         };
6420
6421         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6422
6423         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6424         let channel_reserve = chan_stat.channel_reserve_msat;
6425         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6426         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6427
6428         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6429         let feemsat = 239;
6430         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6431         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6432         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6433         let payment_event = {
6434                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6435                 check_added_monitors!(nodes[0], 1);
6436
6437                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6438                 assert_eq!(events.len(), 1);
6439
6440                 SendEvent::from_event(events.remove(0))
6441         };
6442         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6443         check_added_monitors!(nodes[1], 0);
6444         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6445         expect_pending_htlcs_forwardable!(nodes[1]);
6446
6447         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6448         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6449
6450         // Flush the pending fee update.
6451         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6452         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6453         check_added_monitors!(nodes[2], 1);
6454         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6455         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6456         check_added_monitors!(nodes[1], 2);
6457
6458         // A final RAA message is generated to finalize the fee update.
6459         let events = nodes[1].node.get_and_clear_pending_msg_events();
6460         assert_eq!(events.len(), 1);
6461
6462         let raa_msg = match &events[0] {
6463                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6464                         msg.clone()
6465                 },
6466                 _ => panic!("Unexpected event"),
6467         };
6468
6469         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6470         check_added_monitors!(nodes[2], 1);
6471         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6472
6473         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6474         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6475         assert_eq!(process_htlc_forwards_event.len(), 1);
6476         match &process_htlc_forwards_event[0] {
6477                 &Event::PendingHTLCsForwardable { .. } => {},
6478                 _ => panic!("Unexpected event"),
6479         }
6480
6481         // In response, we call ChannelManager's process_pending_htlc_forwards
6482         nodes[1].node.process_pending_htlc_forwards();
6483         check_added_monitors!(nodes[1], 1);
6484
6485         // This causes the HTLC to be failed backwards.
6486         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6487         assert_eq!(fail_event.len(), 1);
6488         let (fail_msg, commitment_signed) = match &fail_event[0] {
6489                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6490                         assert_eq!(updates.update_add_htlcs.len(), 0);
6491                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6492                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6493                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6494                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6495                 },
6496                 _ => panic!("Unexpected event"),
6497         };
6498
6499         // Pass the failure messages back to nodes[0].
6500         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6501         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6502
6503         // Complete the HTLC failure+removal process.
6504         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6505         check_added_monitors!(nodes[0], 1);
6506         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6507         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6508         check_added_monitors!(nodes[1], 2);
6509         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6510         assert_eq!(final_raa_event.len(), 1);
6511         let raa = match &final_raa_event[0] {
6512                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6513                 _ => panic!("Unexpected event"),
6514         };
6515         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6516         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6517         check_added_monitors!(nodes[0], 1);
6518 }
6519
6520 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6521 // 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.
6522 //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.
6523
6524 #[test]
6525 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6526         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6527         let chanmon_cfgs = create_chanmon_cfgs(2);
6528         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6529         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6530         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6531         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6532
6533         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6534         route.paths[0][0].fee_msat = 100;
6535
6536         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6537                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6538         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6539         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6540 }
6541
6542 #[test]
6543 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6544         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6545         let chanmon_cfgs = create_chanmon_cfgs(2);
6546         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6547         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6548         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6549         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6550
6551         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6552         route.paths[0][0].fee_msat = 0;
6553         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6554                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6555
6556         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6557         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6558 }
6559
6560 #[test]
6561 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6562         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6563         let chanmon_cfgs = create_chanmon_cfgs(2);
6564         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6565         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6566         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6567         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6568
6569         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6570         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6571         check_added_monitors!(nodes[0], 1);
6572         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6573         updates.update_add_htlcs[0].amount_msat = 0;
6574
6575         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6576         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6577         check_closed_broadcast!(nodes[1], true).unwrap();
6578         check_added_monitors!(nodes[1], 1);
6579         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6580 }
6581
6582 #[test]
6583 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6584         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6585         //It is enforced when constructing a route.
6586         let chanmon_cfgs = create_chanmon_cfgs(2);
6587         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6588         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6589         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6590         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6591
6592         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6593                 .with_features(InvoiceFeatures::known());
6594         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6595         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6596         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6597                 assert_eq!(err, &"Channel CLTV overflowed?"));
6598 }
6599
6600 #[test]
6601 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6602         //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.
6603         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6604         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6605         let chanmon_cfgs = create_chanmon_cfgs(2);
6606         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6607         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6608         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6609         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6610         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6611
6612         for i in 0..max_accepted_htlcs {
6613                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6614                 let payment_event = {
6615                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6616                         check_added_monitors!(nodes[0], 1);
6617
6618                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6619                         assert_eq!(events.len(), 1);
6620                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6621                                 assert_eq!(htlcs[0].htlc_id, i);
6622                         } else {
6623                                 assert!(false);
6624                         }
6625                         SendEvent::from_event(events.remove(0))
6626                 };
6627                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6628                 check_added_monitors!(nodes[1], 0);
6629                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6630
6631                 expect_pending_htlcs_forwardable!(nodes[1]);
6632                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6633         }
6634         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6635         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6636                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6637
6638         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6639         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6640 }
6641
6642 #[test]
6643 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6644         //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.
6645         let chanmon_cfgs = create_chanmon_cfgs(2);
6646         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6647         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6648         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6649         let channel_value = 100000;
6650         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6651         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6652
6653         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6654
6655         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6656         // Manually create a route over our max in flight (which our router normally automatically
6657         // limits us to.
6658         route.paths[0][0].fee_msat =  max_in_flight + 1;
6659         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6660                 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)));
6661
6662         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6663         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);
6664
6665         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6666 }
6667
6668 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6669 #[test]
6670 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6671         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6672         let chanmon_cfgs = create_chanmon_cfgs(2);
6673         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6674         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6675         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6676         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6677         let htlc_minimum_msat: u64;
6678         {
6679                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6680                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6681                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6682         }
6683
6684         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6685         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6686         check_added_monitors!(nodes[0], 1);
6687         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6688         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6689         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6690         assert!(nodes[1].node.list_channels().is_empty());
6691         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6692         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()));
6693         check_added_monitors!(nodes[1], 1);
6694         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6695 }
6696
6697 #[test]
6698 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6699         //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
6700         let chanmon_cfgs = create_chanmon_cfgs(2);
6701         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6702         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6703         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6704         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6705
6706         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6707         let channel_reserve = chan_stat.channel_reserve_msat;
6708         let feerate = get_feerate!(nodes[0], chan.2);
6709         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6710         // The 2* and +1 are for the fee spike reserve.
6711         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6712
6713         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6714         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6715         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6716         check_added_monitors!(nodes[0], 1);
6717         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6718
6719         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6720         // at this time channel-initiatee receivers are not required to enforce that senders
6721         // respect the fee_spike_reserve.
6722         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6723         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6724
6725         assert!(nodes[1].node.list_channels().is_empty());
6726         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6727         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6728         check_added_monitors!(nodes[1], 1);
6729         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6730 }
6731
6732 #[test]
6733 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6734         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6735         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6736         let chanmon_cfgs = create_chanmon_cfgs(2);
6737         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6738         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6739         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6740         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6741
6742         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6743         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6744         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6745         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6746         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6747         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6748
6749         let mut msg = msgs::UpdateAddHTLC {
6750                 channel_id: chan.2,
6751                 htlc_id: 0,
6752                 amount_msat: 1000,
6753                 payment_hash: our_payment_hash,
6754                 cltv_expiry: htlc_cltv,
6755                 onion_routing_packet: onion_packet.clone(),
6756         };
6757
6758         for i in 0..super::channel::OUR_MAX_HTLCS {
6759                 msg.htlc_id = i as u64;
6760                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6761         }
6762         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6763         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6764
6765         assert!(nodes[1].node.list_channels().is_empty());
6766         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6767         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6768         check_added_monitors!(nodes[1], 1);
6769         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6770 }
6771
6772 #[test]
6773 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6774         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6775         let chanmon_cfgs = create_chanmon_cfgs(2);
6776         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6777         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6778         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6779         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6780
6781         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6782         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6783         check_added_monitors!(nodes[0], 1);
6784         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6785         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6786         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6787
6788         assert!(nodes[1].node.list_channels().is_empty());
6789         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6790         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6791         check_added_monitors!(nodes[1], 1);
6792         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6793 }
6794
6795 #[test]
6796 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6797         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6798         let chanmon_cfgs = create_chanmon_cfgs(2);
6799         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6800         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6801         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6802
6803         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6804         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6805         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6806         check_added_monitors!(nodes[0], 1);
6807         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6808         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6809         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6810
6811         assert!(nodes[1].node.list_channels().is_empty());
6812         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6813         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6814         check_added_monitors!(nodes[1], 1);
6815         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6816 }
6817
6818 #[test]
6819 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6820         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6821         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6822         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6823         let chanmon_cfgs = create_chanmon_cfgs(2);
6824         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6825         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6826         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6827
6828         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6829         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6830         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6831         check_added_monitors!(nodes[0], 1);
6832         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6833         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6834
6835         //Disconnect and Reconnect
6836         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6837         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6838         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6839         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6840         assert_eq!(reestablish_1.len(), 1);
6841         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6842         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6843         assert_eq!(reestablish_2.len(), 1);
6844         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6845         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6846         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6847         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6848
6849         //Resend HTLC
6850         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6851         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6852         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6853         check_added_monitors!(nodes[1], 1);
6854         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6855
6856         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6857
6858         assert!(nodes[1].node.list_channels().is_empty());
6859         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6860         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6861         check_added_monitors!(nodes[1], 1);
6862         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6863 }
6864
6865 #[test]
6866 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6867         //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.
6868
6869         let chanmon_cfgs = create_chanmon_cfgs(2);
6870         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6871         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6872         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6873         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6874         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6875         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6876
6877         check_added_monitors!(nodes[0], 1);
6878         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6879         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6880
6881         let update_msg = msgs::UpdateFulfillHTLC{
6882                 channel_id: chan.2,
6883                 htlc_id: 0,
6884                 payment_preimage: our_payment_preimage,
6885         };
6886
6887         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6888
6889         assert!(nodes[0].node.list_channels().is_empty());
6890         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6891         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()));
6892         check_added_monitors!(nodes[0], 1);
6893         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6894 }
6895
6896 #[test]
6897 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6898         //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.
6899
6900         let chanmon_cfgs = create_chanmon_cfgs(2);
6901         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6902         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6903         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6904         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6905
6906         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6907         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6908         check_added_monitors!(nodes[0], 1);
6909         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6910         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6911
6912         let update_msg = msgs::UpdateFailHTLC{
6913                 channel_id: chan.2,
6914                 htlc_id: 0,
6915                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6916         };
6917
6918         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6919
6920         assert!(nodes[0].node.list_channels().is_empty());
6921         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6922         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()));
6923         check_added_monitors!(nodes[0], 1);
6924         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6925 }
6926
6927 #[test]
6928 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6929         //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.
6930
6931         let chanmon_cfgs = create_chanmon_cfgs(2);
6932         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6933         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6934         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6935         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6936
6937         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6938         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6939         check_added_monitors!(nodes[0], 1);
6940         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6941         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6942         let update_msg = msgs::UpdateFailMalformedHTLC{
6943                 channel_id: chan.2,
6944                 htlc_id: 0,
6945                 sha256_of_onion: [1; 32],
6946                 failure_code: 0x8000,
6947         };
6948
6949         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6950
6951         assert!(nodes[0].node.list_channels().is_empty());
6952         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6953         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()));
6954         check_added_monitors!(nodes[0], 1);
6955         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6956 }
6957
6958 #[test]
6959 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6960         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6961
6962         let chanmon_cfgs = create_chanmon_cfgs(2);
6963         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6964         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6965         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6966         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6967
6968         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6969
6970         nodes[1].node.claim_funds(our_payment_preimage);
6971         check_added_monitors!(nodes[1], 1);
6972         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6973
6974         let events = nodes[1].node.get_and_clear_pending_msg_events();
6975         assert_eq!(events.len(), 1);
6976         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6977                 match events[0] {
6978                         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, .. } } => {
6979                                 assert!(update_add_htlcs.is_empty());
6980                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6981                                 assert!(update_fail_htlcs.is_empty());
6982                                 assert!(update_fail_malformed_htlcs.is_empty());
6983                                 assert!(update_fee.is_none());
6984                                 update_fulfill_htlcs[0].clone()
6985                         },
6986                         _ => panic!("Unexpected event"),
6987                 }
6988         };
6989
6990         update_fulfill_msg.htlc_id = 1;
6991
6992         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6993
6994         assert!(nodes[0].node.list_channels().is_empty());
6995         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6996         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6997         check_added_monitors!(nodes[0], 1);
6998         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6999 }
7000
7001 #[test]
7002 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
7003         //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.
7004
7005         let chanmon_cfgs = create_chanmon_cfgs(2);
7006         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7007         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7008         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7009         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7010
7011         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
7012
7013         nodes[1].node.claim_funds(our_payment_preimage);
7014         check_added_monitors!(nodes[1], 1);
7015         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7016
7017         let events = nodes[1].node.get_and_clear_pending_msg_events();
7018         assert_eq!(events.len(), 1);
7019         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7020                 match events[0] {
7021                         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, .. } } => {
7022                                 assert!(update_add_htlcs.is_empty());
7023                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7024                                 assert!(update_fail_htlcs.is_empty());
7025                                 assert!(update_fail_malformed_htlcs.is_empty());
7026                                 assert!(update_fee.is_none());
7027                                 update_fulfill_htlcs[0].clone()
7028                         },
7029                         _ => panic!("Unexpected event"),
7030                 }
7031         };
7032
7033         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7034
7035         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7036
7037         assert!(nodes[0].node.list_channels().is_empty());
7038         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7039         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7040         check_added_monitors!(nodes[0], 1);
7041         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7042 }
7043
7044 #[test]
7045 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7046         //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.
7047
7048         let chanmon_cfgs = create_chanmon_cfgs(2);
7049         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7050         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7051         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7052         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7053
7054         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7055         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7056         check_added_monitors!(nodes[0], 1);
7057
7058         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7059         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7060
7061         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7062         check_added_monitors!(nodes[1], 0);
7063         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7064
7065         let events = nodes[1].node.get_and_clear_pending_msg_events();
7066
7067         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7068                 match events[0] {
7069                         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, .. } } => {
7070                                 assert!(update_add_htlcs.is_empty());
7071                                 assert!(update_fulfill_htlcs.is_empty());
7072                                 assert!(update_fail_htlcs.is_empty());
7073                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7074                                 assert!(update_fee.is_none());
7075                                 update_fail_malformed_htlcs[0].clone()
7076                         },
7077                         _ => panic!("Unexpected event"),
7078                 }
7079         };
7080         update_msg.failure_code &= !0x8000;
7081         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7082
7083         assert!(nodes[0].node.list_channels().is_empty());
7084         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7085         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7086         check_added_monitors!(nodes[0], 1);
7087         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7088 }
7089
7090 #[test]
7091 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7092         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7093         //    * 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.
7094
7095         let chanmon_cfgs = create_chanmon_cfgs(3);
7096         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7097         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7098         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7099         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7100         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7101
7102         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7103
7104         //First hop
7105         let mut payment_event = {
7106                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7107                 check_added_monitors!(nodes[0], 1);
7108                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7109                 assert_eq!(events.len(), 1);
7110                 SendEvent::from_event(events.remove(0))
7111         };
7112         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7113         check_added_monitors!(nodes[1], 0);
7114         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7115         expect_pending_htlcs_forwardable!(nodes[1]);
7116         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7117         assert_eq!(events_2.len(), 1);
7118         check_added_monitors!(nodes[1], 1);
7119         payment_event = SendEvent::from_event(events_2.remove(0));
7120         assert_eq!(payment_event.msgs.len(), 1);
7121
7122         //Second Hop
7123         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7124         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7125         check_added_monitors!(nodes[2], 0);
7126         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7127
7128         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7129         assert_eq!(events_3.len(), 1);
7130         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7131                 match events_3[0] {
7132                         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 } } => {
7133                                 assert!(update_add_htlcs.is_empty());
7134                                 assert!(update_fulfill_htlcs.is_empty());
7135                                 assert!(update_fail_htlcs.is_empty());
7136                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7137                                 assert!(update_fee.is_none());
7138                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7139                         },
7140                         _ => panic!("Unexpected event"),
7141                 }
7142         };
7143
7144         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7145
7146         check_added_monitors!(nodes[1], 0);
7147         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7148         expect_pending_htlcs_forwardable!(nodes[1]);
7149         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7150         assert_eq!(events_4.len(), 1);
7151
7152         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7153         match events_4[0] {
7154                 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, .. } } => {
7155                         assert!(update_add_htlcs.is_empty());
7156                         assert!(update_fulfill_htlcs.is_empty());
7157                         assert_eq!(update_fail_htlcs.len(), 1);
7158                         assert!(update_fail_malformed_htlcs.is_empty());
7159                         assert!(update_fee.is_none());
7160                 },
7161                 _ => panic!("Unexpected event"),
7162         };
7163
7164         check_added_monitors!(nodes[1], 1);
7165 }
7166
7167 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7168         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7169         // 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
7170         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7171
7172         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7173         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7174         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7175         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7176         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7177         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7178
7179         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7180
7181         // We route 2 dust-HTLCs between A and B
7182         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7183         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7184         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7185
7186         // Cache one local commitment tx as previous
7187         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7188
7189         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7190         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7191         check_added_monitors!(nodes[1], 0);
7192         expect_pending_htlcs_forwardable!(nodes[1]);
7193         check_added_monitors!(nodes[1], 1);
7194
7195         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7196         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7197         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7198         check_added_monitors!(nodes[0], 1);
7199
7200         // Cache one local commitment tx as lastest
7201         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7202
7203         let events = nodes[0].node.get_and_clear_pending_msg_events();
7204         match events[0] {
7205                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7206                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7207                 },
7208                 _ => panic!("Unexpected event"),
7209         }
7210         match events[1] {
7211                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7212                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7213                 },
7214                 _ => panic!("Unexpected event"),
7215         }
7216
7217         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7218         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7219         if announce_latest {
7220                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7221         } else {
7222                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7223         }
7224
7225         check_closed_broadcast!(nodes[0], true);
7226         check_added_monitors!(nodes[0], 1);
7227         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7228
7229         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7230         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7231         let events = nodes[0].node.get_and_clear_pending_events();
7232         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7233         assert_eq!(events.len(), 2);
7234         let mut first_failed = false;
7235         for event in events {
7236                 match event {
7237                         Event::PaymentPathFailed { payment_hash, .. } => {
7238                                 if payment_hash == payment_hash_1 {
7239                                         assert!(!first_failed);
7240                                         first_failed = true;
7241                                 } else {
7242                                         assert_eq!(payment_hash, payment_hash_2);
7243                                 }
7244                         }
7245                         _ => panic!("Unexpected event"),
7246                 }
7247         }
7248 }
7249
7250 #[test]
7251 fn test_failure_delay_dust_htlc_local_commitment() {
7252         do_test_failure_delay_dust_htlc_local_commitment(true);
7253         do_test_failure_delay_dust_htlc_local_commitment(false);
7254 }
7255
7256 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7257         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7258         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7259         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7260         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7261         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7262         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7263
7264         let chanmon_cfgs = create_chanmon_cfgs(3);
7265         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7266         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7267         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7268         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7269
7270         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7271
7272         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7273         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7274
7275         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7276         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7277
7278         // We revoked bs_commitment_tx
7279         if revoked {
7280                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7281                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7282         }
7283
7284         let mut timeout_tx = Vec::new();
7285         if local {
7286                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7287                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7288                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7289                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7290                 expect_payment_failed!(nodes[0], dust_hash, true);
7291
7292                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7293                 check_closed_broadcast!(nodes[0], true);
7294                 check_added_monitors!(nodes[0], 1);
7295                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7296                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7297                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7298                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7299                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7300                 mine_transaction(&nodes[0], &timeout_tx[0]);
7301                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7302                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7303         } else {
7304                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7305                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7306                 check_closed_broadcast!(nodes[0], true);
7307                 check_added_monitors!(nodes[0], 1);
7308                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7309                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7310
7311                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7312                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7313                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7314                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7315                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7316                 // dust HTLC should have been failed.
7317                 expect_payment_failed!(nodes[0], dust_hash, true);
7318
7319                 if !revoked {
7320                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7321                 } else {
7322                         assert_eq!(timeout_tx[0].lock_time, 0);
7323                 }
7324                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7325                 mine_transaction(&nodes[0], &timeout_tx[0]);
7326                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7327                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7328                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7329         }
7330 }
7331
7332 #[test]
7333 fn test_sweep_outbound_htlc_failure_update() {
7334         do_test_sweep_outbound_htlc_failure_update(false, true);
7335         do_test_sweep_outbound_htlc_failure_update(false, false);
7336         do_test_sweep_outbound_htlc_failure_update(true, false);
7337 }
7338
7339 #[test]
7340 fn test_user_configurable_csv_delay() {
7341         // We test our channel constructors yield errors when we pass them absurd csv delay
7342
7343         let mut low_our_to_self_config = UserConfig::default();
7344         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7345         let mut high_their_to_self_config = UserConfig::default();
7346         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7347         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7348         let chanmon_cfgs = create_chanmon_cfgs(2);
7349         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7350         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7351         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7352
7353         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7354         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7355                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7356                 &low_our_to_self_config, 0, 42)
7357         {
7358                 match error {
7359                         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())); },
7360                         _ => panic!("Unexpected event"),
7361                 }
7362         } else { assert!(false) }
7363
7364         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7365         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7366         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7367         open_channel.to_self_delay = 200;
7368         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7369                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7370                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7371         {
7372                 match error {
7373                         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()));  },
7374                         _ => panic!("Unexpected event"),
7375                 }
7376         } else { assert!(false); }
7377
7378         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7379         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7380         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()));
7381         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7382         accept_channel.to_self_delay = 200;
7383         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7384         let reason_msg;
7385         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7386                 match action {
7387                         &ErrorAction::SendErrorMessage { ref msg } => {
7388                                 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()));
7389                                 reason_msg = msg.data.clone();
7390                         },
7391                         _ => { panic!(); }
7392                 }
7393         } else { panic!(); }
7394         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7395
7396         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7397         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7398         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7399         open_channel.to_self_delay = 200;
7400         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7401                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7402                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7403         {
7404                 match error {
7405                         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())); },
7406                         _ => panic!("Unexpected event"),
7407                 }
7408         } else { assert!(false); }
7409 }
7410
7411 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7412         // When we get a data_loss_protect proving we're behind, we immediately panic as the
7413         // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7414         // panic message informs the user they should force-close without broadcasting, which is tested
7415         // if `reconnect_panicing` is not set.
7416         let persister;
7417         let logger;
7418         let fee_estimator;
7419         let tx_broadcaster;
7420         let chain_source;
7421         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7422         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7423         // during signing due to revoked tx
7424         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7425         let keys_manager = &chanmon_cfgs[0].keys_manager;
7426         let monitor;
7427         let node_state_0;
7428         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7429         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7430         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7431
7432         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7433
7434         // Cache node A state before any channel update
7435         let previous_node_state = nodes[0].node.encode();
7436         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7437         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7438
7439         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7440         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7441
7442         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7443         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7444
7445         // Restore node A from previous state
7446         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7447         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7448         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7449         tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7450         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7451         persister = test_utils::TestPersister::new();
7452         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7453         node_state_0 = {
7454                 let mut channel_monitors = HashMap::new();
7455                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7456                 <(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 {
7457                         keys_manager: keys_manager,
7458                         fee_estimator: &fee_estimator,
7459                         chain_monitor: &monitor,
7460                         logger: &logger,
7461                         tx_broadcaster: &tx_broadcaster,
7462                         default_config: UserConfig::default(),
7463                         channel_monitors,
7464                 }).unwrap().1
7465         };
7466         nodes[0].node = &node_state_0;
7467         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7468         nodes[0].chain_monitor = &monitor;
7469         nodes[0].chain_source = &chain_source;
7470
7471         check_added_monitors!(nodes[0], 1);
7472
7473         if reconnect_panicing {
7474                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7475                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7476
7477                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7478
7479                 // Check we close channel detecting A is fallen-behind
7480                 // Check that we sent the warning message when we detected that A has fallen behind,
7481                 // and give the possibility for A to recover from the warning.
7482                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7483                 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7484                 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7485
7486                 {
7487                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7488                         // The node B should not broadcast the transaction to force close the channel!
7489                         assert!(node_txn.is_empty());
7490                 }
7491
7492                 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7493                 // Check A panics upon seeing proof it has fallen behind.
7494                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7495                 return; // By this point we should have panic'ed!
7496         }
7497
7498         nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7499         check_added_monitors!(nodes[0], 1);
7500         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7501         {
7502                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7503                 assert_eq!(node_txn.len(), 0);
7504         }
7505
7506         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7507                 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7508                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7509                         match action {
7510                                 &ErrorAction::SendErrorMessage { ref msg } => {
7511                                         assert_eq!(msg.data, "Channel force-closed");
7512                                 },
7513                                 _ => panic!("Unexpected event!"),
7514                         }
7515                 } else {
7516                         panic!("Unexpected event {:?}", msg)
7517                 }
7518         }
7519
7520         // after the warning message sent by B, we should not able to
7521         // use the channel, or reconnect with success to the channel.
7522         assert!(nodes[0].node.list_usable_channels().is_empty());
7523         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7524         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7525         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7526
7527         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7528         let mut err_msgs_0 = Vec::with_capacity(1);
7529         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7530                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7531                         match action {
7532                                 &ErrorAction::SendErrorMessage { ref msg } => {
7533                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7534                                         err_msgs_0.push(msg.clone());
7535                                 },
7536                                 _ => panic!("Unexpected event!"),
7537                         }
7538                 } else {
7539                         panic!("Unexpected event!");
7540                 }
7541         }
7542         assert_eq!(err_msgs_0.len(), 1);
7543         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7544         assert!(nodes[1].node.list_usable_channels().is_empty());
7545         check_added_monitors!(nodes[1], 1);
7546         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7547         check_closed_broadcast!(nodes[1], false);
7548 }
7549
7550 #[test]
7551 #[should_panic]
7552 fn test_data_loss_protect_showing_stale_state_panics() {
7553         do_test_data_loss_protect(true);
7554 }
7555
7556 #[test]
7557 fn test_force_close_without_broadcast() {
7558         do_test_data_loss_protect(false);
7559 }
7560
7561 #[test]
7562 fn test_check_htlc_underpaying() {
7563         // Send payment through A -> B but A is maliciously
7564         // sending a probe payment (i.e less than expected value0
7565         // to B, B should refuse payment.
7566
7567         let chanmon_cfgs = create_chanmon_cfgs(2);
7568         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7569         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7570         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7571
7572         // Create some initial channels
7573         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7574
7575         let scorer = test_utils::TestScorer::with_penalty(0);
7576         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7577         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7578         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();
7579         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7580         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7581         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7582         check_added_monitors!(nodes[0], 1);
7583
7584         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7585         assert_eq!(events.len(), 1);
7586         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7587         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7588         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7589
7590         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7591         // and then will wait a second random delay before failing the HTLC back:
7592         expect_pending_htlcs_forwardable!(nodes[1]);
7593         expect_pending_htlcs_forwardable!(nodes[1]);
7594
7595         // Node 3 is expecting payment of 100_000 but received 10_000,
7596         // it should fail htlc like we didn't know the preimage.
7597         nodes[1].node.process_pending_htlc_forwards();
7598
7599         let events = nodes[1].node.get_and_clear_pending_msg_events();
7600         assert_eq!(events.len(), 1);
7601         let (update_fail_htlc, commitment_signed) = match events[0] {
7602                 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 } } => {
7603                         assert!(update_add_htlcs.is_empty());
7604                         assert!(update_fulfill_htlcs.is_empty());
7605                         assert_eq!(update_fail_htlcs.len(), 1);
7606                         assert!(update_fail_malformed_htlcs.is_empty());
7607                         assert!(update_fee.is_none());
7608                         (update_fail_htlcs[0].clone(), commitment_signed)
7609                 },
7610                 _ => panic!("Unexpected event"),
7611         };
7612         check_added_monitors!(nodes[1], 1);
7613
7614         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7615         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7616
7617         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7618         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7619         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7620         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7621 }
7622
7623 #[test]
7624 fn test_announce_disable_channels() {
7625         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7626         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7627
7628         let chanmon_cfgs = create_chanmon_cfgs(2);
7629         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7630         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7631         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7632
7633         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7634         create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7635         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7636
7637         // Disconnect peers
7638         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7639         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7640
7641         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7642         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7643         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7644         assert_eq!(msg_events.len(), 3);
7645         let mut chans_disabled = HashMap::new();
7646         for e in msg_events {
7647                 match e {
7648                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7649                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7650                                 // Check that each channel gets updated exactly once
7651                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7652                                         panic!("Generated ChannelUpdate for wrong chan!");
7653                                 }
7654                         },
7655                         _ => panic!("Unexpected event"),
7656                 }
7657         }
7658         // Reconnect peers
7659         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7660         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7661         assert_eq!(reestablish_1.len(), 3);
7662         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7663         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7664         assert_eq!(reestablish_2.len(), 3);
7665
7666         // Reestablish chan_1
7667         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7668         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7669         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7670         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7671         // Reestablish chan_2
7672         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7673         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7674         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7675         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7676         // Reestablish chan_3
7677         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7678         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7679         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7680         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7681
7682         nodes[0].node.timer_tick_occurred();
7683         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7684         nodes[0].node.timer_tick_occurred();
7685         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7686         assert_eq!(msg_events.len(), 3);
7687         for e in msg_events {
7688                 match e {
7689                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7690                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7691                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7692                                         // Each update should have a higher timestamp than the previous one, replacing
7693                                         // the old one.
7694                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7695                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7696                                 }
7697                         },
7698                         _ => panic!("Unexpected event"),
7699                 }
7700         }
7701         // Check that each channel gets updated exactly once
7702         assert!(chans_disabled.is_empty());
7703 }
7704
7705 #[test]
7706 fn test_bump_penalty_txn_on_revoked_commitment() {
7707         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7708         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7709
7710         let chanmon_cfgs = create_chanmon_cfgs(2);
7711         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7712         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7713         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7714
7715         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7716
7717         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7718         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7719                 .with_features(InvoiceFeatures::known());
7720         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7721         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7722
7723         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7724         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7725         assert_eq!(revoked_txn[0].output.len(), 4);
7726         assert_eq!(revoked_txn[0].input.len(), 1);
7727         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7728         let revoked_txid = revoked_txn[0].txid();
7729
7730         let mut penalty_sum = 0;
7731         for outp in revoked_txn[0].output.iter() {
7732                 if outp.script_pubkey.is_v0_p2wsh() {
7733                         penalty_sum += outp.value;
7734                 }
7735         }
7736
7737         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7738         let header_114 = connect_blocks(&nodes[1], 14);
7739
7740         // Actually revoke tx by claiming a HTLC
7741         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7742         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7743         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7744         check_added_monitors!(nodes[1], 1);
7745
7746         // One or more justice tx should have been broadcast, check it
7747         let penalty_1;
7748         let feerate_1;
7749         {
7750                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7751                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7752                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7753                 assert_eq!(node_txn[0].output.len(), 1);
7754                 check_spends!(node_txn[0], revoked_txn[0]);
7755                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7756                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7757                 penalty_1 = node_txn[0].txid();
7758                 node_txn.clear();
7759         };
7760
7761         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7762         connect_blocks(&nodes[1], 15);
7763         let mut penalty_2 = penalty_1;
7764         let mut feerate_2 = 0;
7765         {
7766                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7767                 assert_eq!(node_txn.len(), 1);
7768                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7769                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7770                         assert_eq!(node_txn[0].output.len(), 1);
7771                         check_spends!(node_txn[0], revoked_txn[0]);
7772                         penalty_2 = node_txn[0].txid();
7773                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7774                         assert_ne!(penalty_2, penalty_1);
7775                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7776                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7777                         // Verify 25% bump heuristic
7778                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7779                         node_txn.clear();
7780                 }
7781         }
7782         assert_ne!(feerate_2, 0);
7783
7784         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7785         connect_blocks(&nodes[1], 1);
7786         let penalty_3;
7787         let mut feerate_3 = 0;
7788         {
7789                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7790                 assert_eq!(node_txn.len(), 1);
7791                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7792                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7793                         assert_eq!(node_txn[0].output.len(), 1);
7794                         check_spends!(node_txn[0], revoked_txn[0]);
7795                         penalty_3 = node_txn[0].txid();
7796                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7797                         assert_ne!(penalty_3, penalty_2);
7798                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7799                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7800                         // Verify 25% bump heuristic
7801                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7802                         node_txn.clear();
7803                 }
7804         }
7805         assert_ne!(feerate_3, 0);
7806
7807         nodes[1].node.get_and_clear_pending_events();
7808         nodes[1].node.get_and_clear_pending_msg_events();
7809 }
7810
7811 #[test]
7812 fn test_bump_penalty_txn_on_revoked_htlcs() {
7813         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7814         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7815
7816         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7817         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7818         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7819         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7820         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7821
7822         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7823         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7824         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7825         let scorer = test_utils::TestScorer::with_penalty(0);
7826         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7827         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7828                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7829         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7830         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7831         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7832                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7833         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7834
7835         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7836         assert_eq!(revoked_local_txn[0].input.len(), 1);
7837         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7838
7839         // Revoke local commitment tx
7840         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7841
7842         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7843         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7844         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7845         check_closed_broadcast!(nodes[1], true);
7846         check_added_monitors!(nodes[1], 1);
7847         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7848         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7849
7850         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7851         assert_eq!(revoked_htlc_txn.len(), 3);
7852         check_spends!(revoked_htlc_txn[1], chan.3);
7853
7854         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7855         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7856         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7857
7858         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7859         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7860         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7861         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7862
7863         // Broadcast set of revoked txn on A
7864         let hash_128 = connect_blocks(&nodes[0], 40);
7865         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7866         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7867         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7868         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7869         let events = nodes[0].node.get_and_clear_pending_events();
7870         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7871         match events[1] {
7872                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7873                 _ => panic!("Unexpected event"),
7874         }
7875         let first;
7876         let feerate_1;
7877         let penalty_txn;
7878         {
7879                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7880                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7881                 // Verify claim tx are spending revoked HTLC txn
7882
7883                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7884                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7885                 // which are included in the same block (they are broadcasted because we scan the
7886                 // transactions linearly and generate claims as we go, they likely should be removed in the
7887                 // future).
7888                 assert_eq!(node_txn[0].input.len(), 1);
7889                 check_spends!(node_txn[0], revoked_local_txn[0]);
7890                 assert_eq!(node_txn[1].input.len(), 1);
7891                 check_spends!(node_txn[1], revoked_local_txn[0]);
7892                 assert_eq!(node_txn[2].input.len(), 1);
7893                 check_spends!(node_txn[2], revoked_local_txn[0]);
7894
7895                 // Each of the three justice transactions claim a separate (single) output of the three
7896                 // available, which we check here:
7897                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7898                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7899                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7900
7901                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7902                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7903
7904                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7905                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7906                 // a remote commitment tx has already been confirmed).
7907                 check_spends!(node_txn[3], chan.3);
7908
7909                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7910                 // output, checked above).
7911                 assert_eq!(node_txn[4].input.len(), 2);
7912                 assert_eq!(node_txn[4].output.len(), 1);
7913                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7914
7915                 first = node_txn[4].txid();
7916                 // Store both feerates for later comparison
7917                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7918                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7919                 penalty_txn = vec![node_txn[2].clone()];
7920                 node_txn.clear();
7921         }
7922
7923         // Connect one more block to see if bumped penalty are issued for HTLC txn
7924         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7925         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7926         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7927         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7928         {
7929                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7930                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7931
7932                 check_spends!(node_txn[0], revoked_local_txn[0]);
7933                 check_spends!(node_txn[1], revoked_local_txn[0]);
7934                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7935                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7936                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7937                 } else {
7938                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7939                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7940                 }
7941
7942                 node_txn.clear();
7943         };
7944
7945         // Few more blocks to confirm penalty txn
7946         connect_blocks(&nodes[0], 4);
7947         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7948         let header_144 = connect_blocks(&nodes[0], 9);
7949         let node_txn = {
7950                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7951                 assert_eq!(node_txn.len(), 1);
7952
7953                 assert_eq!(node_txn[0].input.len(), 2);
7954                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7955                 // Verify bumped tx is different and 25% bump heuristic
7956                 assert_ne!(first, node_txn[0].txid());
7957                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7958                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7959                 assert!(feerate_2 * 100 > feerate_1 * 125);
7960                 let txn = vec![node_txn[0].clone()];
7961                 node_txn.clear();
7962                 txn
7963         };
7964         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7965         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7966         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7967         connect_blocks(&nodes[0], 20);
7968         {
7969                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7970                 // We verify than no new transaction has been broadcast because previously
7971                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7972                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7973                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7974                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7975                 // up bumped justice generation.
7976                 assert_eq!(node_txn.len(), 0);
7977                 node_txn.clear();
7978         }
7979         check_closed_broadcast!(nodes[0], true);
7980         check_added_monitors!(nodes[0], 1);
7981 }
7982
7983 #[test]
7984 fn test_bump_penalty_txn_on_remote_commitment() {
7985         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7986         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7987
7988         // Create 2 HTLCs
7989         // Provide preimage for one
7990         // Check aggregation
7991
7992         let chanmon_cfgs = create_chanmon_cfgs(2);
7993         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7994         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7995         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7996
7997         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7998         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7999         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8000
8001         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8002         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8003         assert_eq!(remote_txn[0].output.len(), 4);
8004         assert_eq!(remote_txn[0].input.len(), 1);
8005         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8006
8007         // Claim a HTLC without revocation (provide B monitor with preimage)
8008         nodes[1].node.claim_funds(payment_preimage);
8009         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
8010         mine_transaction(&nodes[1], &remote_txn[0]);
8011         check_added_monitors!(nodes[1], 2);
8012         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8013
8014         // One or more claim tx should have been broadcast, check it
8015         let timeout;
8016         let preimage;
8017         let preimage_bump;
8018         let feerate_timeout;
8019         let feerate_preimage;
8020         {
8021                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8022                 // 9 transactions including:
8023                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8024                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8025                 // 2 * HTLC-Success (one RBF bump we'll check later)
8026                 // 1 * HTLC-Timeout
8027                 assert_eq!(node_txn.len(), 8);
8028                 assert_eq!(node_txn[0].input.len(), 1);
8029                 assert_eq!(node_txn[6].input.len(), 1);
8030                 check_spends!(node_txn[0], remote_txn[0]);
8031                 check_spends!(node_txn[6], remote_txn[0]);
8032
8033                 check_spends!(node_txn[1], chan.3);
8034                 check_spends!(node_txn[2], node_txn[1]);
8035
8036                 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
8037                         preimage_bump = node_txn[3].clone();
8038                         check_spends!(node_txn[3], remote_txn[0]);
8039
8040                         assert_eq!(node_txn[1], node_txn[4]);
8041                         assert_eq!(node_txn[2], node_txn[5]);
8042                 } else {
8043                         preimage_bump = node_txn[7].clone();
8044                         check_spends!(node_txn[7], remote_txn[0]);
8045                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8046
8047                         assert_eq!(node_txn[1], node_txn[3]);
8048                         assert_eq!(node_txn[2], node_txn[4]);
8049                 }
8050
8051                 timeout = node_txn[6].txid();
8052                 let index = node_txn[6].input[0].previous_output.vout;
8053                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8054                 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8055
8056                 preimage = node_txn[0].txid();
8057                 let index = node_txn[0].input[0].previous_output.vout;
8058                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8059                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8060
8061                 node_txn.clear();
8062         };
8063         assert_ne!(feerate_timeout, 0);
8064         assert_ne!(feerate_preimage, 0);
8065
8066         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8067         connect_blocks(&nodes[1], 15);
8068         {
8069                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8070                 assert_eq!(node_txn.len(), 1);
8071                 assert_eq!(node_txn[0].input.len(), 1);
8072                 assert_eq!(preimage_bump.input.len(), 1);
8073                 check_spends!(node_txn[0], remote_txn[0]);
8074                 check_spends!(preimage_bump, remote_txn[0]);
8075
8076                 let index = preimage_bump.input[0].previous_output.vout;
8077                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8078                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8079                 assert!(new_feerate * 100 > feerate_timeout * 125);
8080                 assert_ne!(timeout, preimage_bump.txid());
8081
8082                 let index = node_txn[0].input[0].previous_output.vout;
8083                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8084                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8085                 assert!(new_feerate * 100 > feerate_preimage * 125);
8086                 assert_ne!(preimage, node_txn[0].txid());
8087
8088                 node_txn.clear();
8089         }
8090
8091         nodes[1].node.get_and_clear_pending_events();
8092         nodes[1].node.get_and_clear_pending_msg_events();
8093 }
8094
8095 #[test]
8096 fn test_counterparty_raa_skip_no_crash() {
8097         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8098         // commitment transaction, we would have happily carried on and provided them the next
8099         // commitment transaction based on one RAA forward. This would probably eventually have led to
8100         // channel closure, but it would not have resulted in funds loss. Still, our
8101         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8102         // check simply that the channel is closed in response to such an RAA, but don't check whether
8103         // we decide to punish our counterparty for revoking their funds (as we don't currently
8104         // implement that).
8105         let chanmon_cfgs = create_chanmon_cfgs(2);
8106         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8107         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8108         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8109         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8110
8111         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8112         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8113
8114         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8115
8116         // Make signer believe we got a counterparty signature, so that it allows the revocation
8117         keys.get_enforcement_state().last_holder_commitment -= 1;
8118         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8119
8120         // Must revoke without gaps
8121         keys.get_enforcement_state().last_holder_commitment -= 1;
8122         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8123
8124         keys.get_enforcement_state().last_holder_commitment -= 1;
8125         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8126                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8127
8128         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8129                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8130         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8131         check_added_monitors!(nodes[1], 1);
8132         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8133 }
8134
8135 #[test]
8136 fn test_bump_txn_sanitize_tracking_maps() {
8137         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8138         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8139
8140         let chanmon_cfgs = create_chanmon_cfgs(2);
8141         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8142         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8143         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8144
8145         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8146         // Lock HTLC in both directions
8147         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8148         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8149
8150         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8151         assert_eq!(revoked_local_txn[0].input.len(), 1);
8152         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8153
8154         // Revoke local commitment tx
8155         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8156
8157         // Broadcast set of revoked txn on A
8158         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8159         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8160         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8161
8162         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8163         check_closed_broadcast!(nodes[0], true);
8164         check_added_monitors!(nodes[0], 1);
8165         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8166         let penalty_txn = {
8167                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8168                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8169                 check_spends!(node_txn[0], revoked_local_txn[0]);
8170                 check_spends!(node_txn[1], revoked_local_txn[0]);
8171                 check_spends!(node_txn[2], revoked_local_txn[0]);
8172                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8173                 node_txn.clear();
8174                 penalty_txn
8175         };
8176         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8177         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8178         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8179         {
8180                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8181                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8182                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8183         }
8184 }
8185
8186 #[test]
8187 fn test_pending_claimed_htlc_no_balance_underflow() {
8188         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8189         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8190         let chanmon_cfgs = create_chanmon_cfgs(2);
8191         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8192         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8193         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8194         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8195
8196         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8197         nodes[1].node.claim_funds(payment_preimage);
8198         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8199         check_added_monitors!(nodes[1], 1);
8200         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8201
8202         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8203         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8204         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8205         check_added_monitors!(nodes[0], 1);
8206         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8207
8208         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8209         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8210         // can get our balance.
8211
8212         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8213         // the public key of the only hop. This works around ChannelDetails not showing the
8214         // almost-claimed HTLC as available balance.
8215         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8216         route.payment_params = None; // This is all wrong, but unnecessary
8217         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8218         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8219         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8220
8221         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8222 }
8223
8224 #[test]
8225 fn test_channel_conf_timeout() {
8226         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8227         // confirm within 2016 blocks, as recommended by BOLT 2.
8228         let chanmon_cfgs = create_chanmon_cfgs(2);
8229         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8230         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8231         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8232
8233         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8234
8235         // The outbound node should wait forever for confirmation:
8236         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8237         // copied here instead of directly referencing the constant.
8238         connect_blocks(&nodes[0], 2016);
8239         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8240
8241         // The inbound node should fail the channel after exactly 2016 blocks
8242         connect_blocks(&nodes[1], 2015);
8243         check_added_monitors!(nodes[1], 0);
8244         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8245
8246         connect_blocks(&nodes[1], 1);
8247         check_added_monitors!(nodes[1], 1);
8248         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8249         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8250         assert_eq!(close_ev.len(), 1);
8251         match close_ev[0] {
8252                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8253                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8254                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8255                 },
8256                 _ => panic!("Unexpected event"),
8257         }
8258 }
8259
8260 #[test]
8261 fn test_override_channel_config() {
8262         let chanmon_cfgs = create_chanmon_cfgs(2);
8263         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8264         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8265         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8266
8267         // Node0 initiates a channel to node1 using the override config.
8268         let mut override_config = UserConfig::default();
8269         override_config.channel_handshake_config.our_to_self_delay = 200;
8270
8271         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8272
8273         // Assert the channel created by node0 is using the override config.
8274         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8275         assert_eq!(res.channel_flags, 0);
8276         assert_eq!(res.to_self_delay, 200);
8277 }
8278
8279 #[test]
8280 fn test_override_0msat_htlc_minimum() {
8281         let mut zero_config = UserConfig::default();
8282         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8283         let chanmon_cfgs = create_chanmon_cfgs(2);
8284         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8285         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8286         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8287
8288         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8289         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8290         assert_eq!(res.htlc_minimum_msat, 1);
8291
8292         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8293         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8294         assert_eq!(res.htlc_minimum_msat, 1);
8295 }
8296
8297 #[test]
8298 fn test_channel_update_has_correct_htlc_maximum_msat() {
8299         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8300         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8301         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8302         // 90% of the `channel_value`.
8303         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8304
8305         let mut config_30_percent = UserConfig::default();
8306         config_30_percent.channel_handshake_config.announced_channel = true;
8307         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8308         let mut config_50_percent = UserConfig::default();
8309         config_50_percent.channel_handshake_config.announced_channel = true;
8310         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8311         let mut config_95_percent = UserConfig::default();
8312         config_95_percent.channel_handshake_config.announced_channel = true;
8313         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8314         let mut config_100_percent = UserConfig::default();
8315         config_100_percent.channel_handshake_config.announced_channel = true;
8316         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8317
8318         let chanmon_cfgs = create_chanmon_cfgs(4);
8319         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8320         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)]);
8321         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8322
8323         let channel_value_satoshis = 100000;
8324         let channel_value_msat = channel_value_satoshis * 1000;
8325         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8326         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8327         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8328
8329         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());
8330         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());
8331
8332         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8333         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8334         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8335         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8336         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8337         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8338
8339         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8340         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8341         // `channel_value`.
8342         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8343         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8344         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8345         // `channel_value`.
8346         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8347 }
8348
8349 #[test]
8350 fn test_manually_accept_inbound_channel_request() {
8351         let mut manually_accept_conf = UserConfig::default();
8352         manually_accept_conf.manually_accept_inbound_channels = true;
8353         let chanmon_cfgs = create_chanmon_cfgs(2);
8354         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8355         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8356         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8357
8358         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8359         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8360
8361         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8362
8363         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8364         // accepting the inbound channel request.
8365         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8366
8367         let events = nodes[1].node.get_and_clear_pending_events();
8368         match events[0] {
8369                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8370                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8371                 }
8372                 _ => panic!("Unexpected event"),
8373         }
8374
8375         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8376         assert_eq!(accept_msg_ev.len(), 1);
8377
8378         match accept_msg_ev[0] {
8379                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8380                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8381                 }
8382                 _ => panic!("Unexpected event"),
8383         }
8384
8385         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8386
8387         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8388         assert_eq!(close_msg_ev.len(), 1);
8389
8390         let events = nodes[1].node.get_and_clear_pending_events();
8391         match events[0] {
8392                 Event::ChannelClosed { user_channel_id, .. } => {
8393                         assert_eq!(user_channel_id, 23);
8394                 }
8395                 _ => panic!("Unexpected event"),
8396         }
8397 }
8398
8399 #[test]
8400 fn test_manually_reject_inbound_channel_request() {
8401         let mut manually_accept_conf = UserConfig::default();
8402         manually_accept_conf.manually_accept_inbound_channels = true;
8403         let chanmon_cfgs = create_chanmon_cfgs(2);
8404         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8405         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8406         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8407
8408         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8409         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8410
8411         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8412
8413         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8414         // rejecting the inbound channel request.
8415         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8416
8417         let events = nodes[1].node.get_and_clear_pending_events();
8418         match events[0] {
8419                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8420                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8421                 }
8422                 _ => panic!("Unexpected event"),
8423         }
8424
8425         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8426         assert_eq!(close_msg_ev.len(), 1);
8427
8428         match close_msg_ev[0] {
8429                 MessageSendEvent::HandleError { ref node_id, .. } => {
8430                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8431                 }
8432                 _ => panic!("Unexpected event"),
8433         }
8434         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8435 }
8436
8437 #[test]
8438 fn test_reject_funding_before_inbound_channel_accepted() {
8439         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8440         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8441         // the node operator before the counterparty sends a `FundingCreated` message. If a
8442         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8443         // and the channel should be closed.
8444         let mut manually_accept_conf = UserConfig::default();
8445         manually_accept_conf.manually_accept_inbound_channels = true;
8446         let chanmon_cfgs = create_chanmon_cfgs(2);
8447         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8448         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8449         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8450
8451         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8452         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8453         let temp_channel_id = res.temporary_channel_id;
8454
8455         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8456
8457         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8458         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8459
8460         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8461         nodes[1].node.get_and_clear_pending_events();
8462
8463         // Get the `AcceptChannel` message of `nodes[1]` without calling
8464         // `ChannelManager::accept_inbound_channel`, which generates a
8465         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8466         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8467         // succeed when `nodes[0]` is passed to it.
8468         {
8469                 let mut lock;
8470                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8471                 let accept_chan_msg = channel.get_accept_channel_message();
8472                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8473         }
8474
8475         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8476
8477         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8478         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8479
8480         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8481         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8482
8483         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8484         assert_eq!(close_msg_ev.len(), 1);
8485
8486         let expected_err = "FundingCreated message received before the channel was accepted";
8487         match close_msg_ev[0] {
8488                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8489                         assert_eq!(msg.channel_id, temp_channel_id);
8490                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8491                         assert_eq!(msg.data, expected_err);
8492                 }
8493                 _ => panic!("Unexpected event"),
8494         }
8495
8496         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8497 }
8498
8499 #[test]
8500 fn test_can_not_accept_inbound_channel_twice() {
8501         let mut manually_accept_conf = UserConfig::default();
8502         manually_accept_conf.manually_accept_inbound_channels = true;
8503         let chanmon_cfgs = create_chanmon_cfgs(2);
8504         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8505         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8506         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8507
8508         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8509         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8510
8511         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8512
8513         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8514         // accepting the inbound channel request.
8515         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8516
8517         let events = nodes[1].node.get_and_clear_pending_events();
8518         match events[0] {
8519                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8520                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8521                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8522                         match api_res {
8523                                 Err(APIError::APIMisuseError { err }) => {
8524                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8525                                 },
8526                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8527                                 Err(_) => panic!("Unexpected Error"),
8528                         }
8529                 }
8530                 _ => panic!("Unexpected event"),
8531         }
8532
8533         // Ensure that the channel wasn't closed after attempting to accept it twice.
8534         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8535         assert_eq!(accept_msg_ev.len(), 1);
8536
8537         match accept_msg_ev[0] {
8538                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8539                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8540                 }
8541                 _ => panic!("Unexpected event"),
8542         }
8543 }
8544
8545 #[test]
8546 fn test_can_not_accept_unknown_inbound_channel() {
8547         let chanmon_cfg = create_chanmon_cfgs(2);
8548         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8549         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8550         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8551
8552         let unknown_channel_id = [0; 32];
8553         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8554         match api_res {
8555                 Err(APIError::ChannelUnavailable { err }) => {
8556                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8557                 },
8558                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8559                 Err(_) => panic!("Unexpected Error"),
8560         }
8561 }
8562
8563 #[test]
8564 fn test_simple_mpp() {
8565         // Simple test of sending a multi-path payment.
8566         let chanmon_cfgs = create_chanmon_cfgs(4);
8567         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8568         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8569         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8570
8571         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8572         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8573         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8574         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8575
8576         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8577         let path = route.paths[0].clone();
8578         route.paths.push(path);
8579         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8580         route.paths[0][0].short_channel_id = chan_1_id;
8581         route.paths[0][1].short_channel_id = chan_3_id;
8582         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8583         route.paths[1][0].short_channel_id = chan_2_id;
8584         route.paths[1][1].short_channel_id = chan_4_id;
8585         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8586         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8587 }
8588
8589 #[test]
8590 fn test_preimage_storage() {
8591         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8592         let chanmon_cfgs = create_chanmon_cfgs(2);
8593         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8594         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8595         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8596
8597         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8598
8599         {
8600                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8601                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8602                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8603                 check_added_monitors!(nodes[0], 1);
8604                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8605                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8606                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8607                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8608         }
8609         // Note that after leaving the above scope we have no knowledge of any arguments or return
8610         // values from previous calls.
8611         expect_pending_htlcs_forwardable!(nodes[1]);
8612         let events = nodes[1].node.get_and_clear_pending_events();
8613         assert_eq!(events.len(), 1);
8614         match events[0] {
8615                 Event::PaymentReceived { ref purpose, .. } => {
8616                         match &purpose {
8617                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8618                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8619                                 },
8620                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8621                         }
8622                 },
8623                 _ => panic!("Unexpected event"),
8624         }
8625 }
8626
8627 #[test]
8628 #[allow(deprecated)]
8629 fn test_secret_timeout() {
8630         // Simple test of payment secret storage time outs. After
8631         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8632         let chanmon_cfgs = create_chanmon_cfgs(2);
8633         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8634         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8635         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8636
8637         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8638
8639         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8640
8641         // We should fail to register the same payment hash twice, at least until we've connected a
8642         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8643         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8644                 assert_eq!(err, "Duplicate payment hash");
8645         } else { panic!(); }
8646         let mut block = {
8647                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8648                 Block {
8649                         header: BlockHeader {
8650                                 version: 0x2000000,
8651                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8652                                 merkle_root: Default::default(),
8653                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8654                         txdata: vec![],
8655                 }
8656         };
8657         connect_block(&nodes[1], &block);
8658         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8659                 assert_eq!(err, "Duplicate payment hash");
8660         } else { panic!(); }
8661
8662         // If we then connect the second block, we should be able to register the same payment hash
8663         // again (this time getting a new payment secret).
8664         block.header.prev_blockhash = block.header.block_hash();
8665         block.header.time += 1;
8666         connect_block(&nodes[1], &block);
8667         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8668         assert_ne!(payment_secret_1, our_payment_secret);
8669
8670         {
8671                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8672                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8673                 check_added_monitors!(nodes[0], 1);
8674                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8675                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8676                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8677                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8678         }
8679         // Note that after leaving the above scope we have no knowledge of any arguments or return
8680         // values from previous calls.
8681         expect_pending_htlcs_forwardable!(nodes[1]);
8682         let events = nodes[1].node.get_and_clear_pending_events();
8683         assert_eq!(events.len(), 1);
8684         match events[0] {
8685                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8686                         assert!(payment_preimage.is_none());
8687                         assert_eq!(payment_secret, our_payment_secret);
8688                         // We don't actually have the payment preimage with which to claim this payment!
8689                 },
8690                 _ => panic!("Unexpected event"),
8691         }
8692 }
8693
8694 #[test]
8695 fn test_bad_secret_hash() {
8696         // Simple test of unregistered payment hash/invalid payment secret handling
8697         let chanmon_cfgs = create_chanmon_cfgs(2);
8698         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8699         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8700         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8701
8702         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8703
8704         let random_payment_hash = PaymentHash([42; 32]);
8705         let random_payment_secret = PaymentSecret([43; 32]);
8706         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8707         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8708
8709         // All the below cases should end up being handled exactly identically, so we macro the
8710         // resulting events.
8711         macro_rules! handle_unknown_invalid_payment_data {
8712                 () => {
8713                         check_added_monitors!(nodes[0], 1);
8714                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8715                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8716                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8717                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8718
8719                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8720                         // again to process the pending backwards-failure of the HTLC
8721                         expect_pending_htlcs_forwardable!(nodes[1]);
8722                         expect_pending_htlcs_forwardable!(nodes[1]);
8723                         check_added_monitors!(nodes[1], 1);
8724
8725                         // We should fail the payment back
8726                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8727                         match events.pop().unwrap() {
8728                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8729                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8730                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8731                                 },
8732                                 _ => panic!("Unexpected event"),
8733                         }
8734                 }
8735         }
8736
8737         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8738         // Error data is the HTLC value (100,000) and current block height
8739         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8740
8741         // Send a payment with the right payment hash but the wrong payment secret
8742         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8743         handle_unknown_invalid_payment_data!();
8744         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8745
8746         // Send a payment with a random payment hash, but the right payment secret
8747         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8748         handle_unknown_invalid_payment_data!();
8749         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8750
8751         // Send a payment with a random payment hash and random payment secret
8752         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8753         handle_unknown_invalid_payment_data!();
8754         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8755 }
8756
8757 #[test]
8758 fn test_update_err_monitor_lockdown() {
8759         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8760         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8761         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8762         //
8763         // This scenario may happen in a watchtower setup, where watchtower process a block height
8764         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8765         // commitment at same time.
8766
8767         let chanmon_cfgs = create_chanmon_cfgs(2);
8768         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8769         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8770         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8771
8772         // Create some initial channel
8773         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8774         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8775
8776         // Rebalance the network to generate htlc in the two directions
8777         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8778
8779         // Route a HTLC from node 0 to node 1 (but don't settle)
8780         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8781
8782         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8783         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8784         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8785         let persister = test_utils::TestPersister::new();
8786         let watchtower = {
8787                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8788                 let mut w = test_utils::TestVecWriter(Vec::new());
8789                 monitor.write(&mut w).unwrap();
8790                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8791                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8792                 assert!(new_monitor == *monitor);
8793                 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);
8794                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8795                 watchtower
8796         };
8797         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8798         let block = Block { header, txdata: vec![] };
8799         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8800         // transaction lock time requirements here.
8801         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8802         watchtower.chain_monitor.block_connected(&block, 200);
8803
8804         // Try to update ChannelMonitor
8805         nodes[1].node.claim_funds(preimage);
8806         check_added_monitors!(nodes[1], 1);
8807         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8808
8809         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8810         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8811         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8812         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8813                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8814                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8815                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8816                 } else { assert!(false); }
8817         } else { assert!(false); };
8818         // Our local monitor is in-sync and hasn't processed yet timeout
8819         check_added_monitors!(nodes[0], 1);
8820         let events = nodes[0].node.get_and_clear_pending_events();
8821         assert_eq!(events.len(), 1);
8822 }
8823
8824 #[test]
8825 fn test_concurrent_monitor_claim() {
8826         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8827         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8828         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8829         // state N+1 confirms. Alice claims output from state N+1.
8830
8831         let chanmon_cfgs = create_chanmon_cfgs(2);
8832         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8833         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8834         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8835
8836         // Create some initial channel
8837         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8838         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8839
8840         // Rebalance the network to generate htlc in the two directions
8841         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8842
8843         // Route a HTLC from node 0 to node 1 (but don't settle)
8844         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8845
8846         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8847         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8848         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8849         let persister = test_utils::TestPersister::new();
8850         let watchtower_alice = {
8851                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8852                 let mut w = test_utils::TestVecWriter(Vec::new());
8853                 monitor.write(&mut w).unwrap();
8854                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8855                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8856                 assert!(new_monitor == *monitor);
8857                 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);
8858                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8859                 watchtower
8860         };
8861         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8862         let block = Block { header, txdata: vec![] };
8863         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8864         // transaction lock time requirements here.
8865         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));
8866         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8867
8868         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8869         {
8870                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8871                 assert_eq!(txn.len(), 2);
8872                 txn.clear();
8873         }
8874
8875         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8876         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8877         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8878         let persister = test_utils::TestPersister::new();
8879         let watchtower_bob = {
8880                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8881                 let mut w = test_utils::TestVecWriter(Vec::new());
8882                 monitor.write(&mut w).unwrap();
8883                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8884                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8885                 assert!(new_monitor == *monitor);
8886                 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);
8887                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8888                 watchtower
8889         };
8890         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8891         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8892
8893         // Route another payment to generate another update with still previous HTLC pending
8894         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8895         {
8896                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8897         }
8898         check_added_monitors!(nodes[1], 1);
8899
8900         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8901         assert_eq!(updates.update_add_htlcs.len(), 1);
8902         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8903         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8904                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8905                         // Watchtower Alice should already have seen the block and reject the update
8906                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8907                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8908                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8909                 } else { assert!(false); }
8910         } else { assert!(false); };
8911         // Our local monitor is in-sync and hasn't processed yet timeout
8912         check_added_monitors!(nodes[0], 1);
8913
8914         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8915         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8916         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8917
8918         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8919         let bob_state_y;
8920         {
8921                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8922                 assert_eq!(txn.len(), 2);
8923                 bob_state_y = txn[0].clone();
8924                 txn.clear();
8925         };
8926
8927         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8928         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8929         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);
8930         {
8931                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8932                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8933                 // the onchain detection of the HTLC output
8934                 assert_eq!(htlc_txn.len(), 2);
8935                 check_spends!(htlc_txn[0], bob_state_y);
8936                 check_spends!(htlc_txn[1], bob_state_y);
8937         }
8938 }
8939
8940 #[test]
8941 fn test_pre_lockin_no_chan_closed_update() {
8942         // Test that if a peer closes a channel in response to a funding_created message we don't
8943         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8944         // message).
8945         //
8946         // Doing so would imply a channel monitor update before the initial channel monitor
8947         // registration, violating our API guarantees.
8948         //
8949         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8950         // then opening a second channel with the same funding output as the first (which is not
8951         // rejected because the first channel does not exist in the ChannelManager) and closing it
8952         // before receiving funding_signed.
8953         let chanmon_cfgs = create_chanmon_cfgs(2);
8954         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8955         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8956         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8957
8958         // Create an initial channel
8959         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8960         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8961         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8962         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8963         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8964
8965         // Move the first channel through the funding flow...
8966         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8967
8968         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8969         check_added_monitors!(nodes[0], 0);
8970
8971         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8972         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8973         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8974         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8975         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8976 }
8977
8978 #[test]
8979 fn test_htlc_no_detection() {
8980         // This test is a mutation to underscore the detection logic bug we had
8981         // before #653. HTLC value routed is above the remaining balance, thus
8982         // inverting HTLC and `to_remote` output. HTLC will come second and
8983         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8984         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8985         // outputs order detection for correct spending children filtring.
8986
8987         let chanmon_cfgs = create_chanmon_cfgs(2);
8988         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8989         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8990         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8991
8992         // Create some initial channels
8993         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8994
8995         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8996         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8997         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8998         assert_eq!(local_txn[0].input.len(), 1);
8999         assert_eq!(local_txn[0].output.len(), 3);
9000         check_spends!(local_txn[0], chan_1.3);
9001
9002         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9003         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9004         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
9005         // We deliberately connect the local tx twice as this should provoke a failure calling
9006         // this test before #653 fix.
9007         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);
9008         check_closed_broadcast!(nodes[0], true);
9009         check_added_monitors!(nodes[0], 1);
9010         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
9011         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9012
9013         let htlc_timeout = {
9014                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9015                 assert_eq!(node_txn[1].input.len(), 1);
9016                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9017                 check_spends!(node_txn[1], local_txn[0]);
9018                 node_txn[1].clone()
9019         };
9020
9021         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9022         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9023         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9024         expect_payment_failed!(nodes[0], our_payment_hash, true);
9025 }
9026
9027 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9028         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9029         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9030         // Carol, Alice would be the upstream node, and Carol the downstream.)
9031         //
9032         // Steps of the test:
9033         // 1) Alice sends a HTLC to Carol through Bob.
9034         // 2) Carol doesn't settle the HTLC.
9035         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9036         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9037         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9038         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9039         // 5) Carol release the preimage to Bob off-chain.
9040         // 6) Bob claims the offered output on the broadcasted commitment.
9041         let chanmon_cfgs = create_chanmon_cfgs(3);
9042         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9043         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9044         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9045
9046         // Create some initial channels
9047         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9048         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9049
9050         // Steps (1) and (2):
9051         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9052         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9053
9054         // Check that Alice's commitment transaction now contains an output for this HTLC.
9055         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9056         check_spends!(alice_txn[0], chan_ab.3);
9057         assert_eq!(alice_txn[0].output.len(), 2);
9058         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9059         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9060         assert_eq!(alice_txn.len(), 2);
9061
9062         // Steps (3) and (4):
9063         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9064         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9065         let mut force_closing_node = 0; // Alice force-closes
9066         let mut counterparty_node = 1; // Bob if Alice force-closes
9067
9068         // Bob force-closes
9069         if !broadcast_alice {
9070                 force_closing_node = 1;
9071                 counterparty_node = 0;
9072         }
9073         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9074         check_closed_broadcast!(nodes[force_closing_node], true);
9075         check_added_monitors!(nodes[force_closing_node], 1);
9076         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9077         if go_onchain_before_fulfill {
9078                 let txn_to_broadcast = match broadcast_alice {
9079                         true => alice_txn.clone(),
9080                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9081                 };
9082                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9083                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9084                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9085                 if broadcast_alice {
9086                         check_closed_broadcast!(nodes[1], true);
9087                         check_added_monitors!(nodes[1], 1);
9088                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9089                 }
9090                 assert_eq!(bob_txn.len(), 1);
9091                 check_spends!(bob_txn[0], chan_ab.3);
9092         }
9093
9094         // Step (5):
9095         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9096         // process of removing the HTLC from their commitment transactions.
9097         nodes[2].node.claim_funds(payment_preimage);
9098         check_added_monitors!(nodes[2], 1);
9099         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9100
9101         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9102         assert!(carol_updates.update_add_htlcs.is_empty());
9103         assert!(carol_updates.update_fail_htlcs.is_empty());
9104         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9105         assert!(carol_updates.update_fee.is_none());
9106         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9107
9108         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9109         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9110         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9111         if !go_onchain_before_fulfill && broadcast_alice {
9112                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9113                 assert_eq!(events.len(), 1);
9114                 match events[0] {
9115                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9116                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9117                         },
9118                         _ => panic!("Unexpected event"),
9119                 };
9120         }
9121         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9122         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9123         // Carol<->Bob's updated commitment transaction info.
9124         check_added_monitors!(nodes[1], 2);
9125
9126         let events = nodes[1].node.get_and_clear_pending_msg_events();
9127         assert_eq!(events.len(), 2);
9128         let bob_revocation = match events[0] {
9129                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9130                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9131                         (*msg).clone()
9132                 },
9133                 _ => panic!("Unexpected event"),
9134         };
9135         let bob_updates = match events[1] {
9136                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9137                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9138                         (*updates).clone()
9139                 },
9140                 _ => panic!("Unexpected event"),
9141         };
9142
9143         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9144         check_added_monitors!(nodes[2], 1);
9145         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9146         check_added_monitors!(nodes[2], 1);
9147
9148         let events = nodes[2].node.get_and_clear_pending_msg_events();
9149         assert_eq!(events.len(), 1);
9150         let carol_revocation = match events[0] {
9151                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9152                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9153                         (*msg).clone()
9154                 },
9155                 _ => panic!("Unexpected event"),
9156         };
9157         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9158         check_added_monitors!(nodes[1], 1);
9159
9160         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9161         // here's where we put said channel's commitment tx on-chain.
9162         let mut txn_to_broadcast = alice_txn.clone();
9163         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9164         if !go_onchain_before_fulfill {
9165                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9166                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9167                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9168                 if broadcast_alice {
9169                         check_closed_broadcast!(nodes[1], true);
9170                         check_added_monitors!(nodes[1], 1);
9171                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9172                 }
9173                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9174                 if broadcast_alice {
9175                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9176                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9177                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9178                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9179                         // broadcasted.
9180                         assert_eq!(bob_txn.len(), 3);
9181                         check_spends!(bob_txn[1], chan_ab.3);
9182                 } else {
9183                         assert_eq!(bob_txn.len(), 2);
9184                         check_spends!(bob_txn[0], chan_ab.3);
9185                 }
9186         }
9187
9188         // Step (6):
9189         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9190         // broadcasted commitment transaction.
9191         {
9192                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9193                 if go_onchain_before_fulfill {
9194                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9195                         assert_eq!(bob_txn.len(), 2);
9196                 }
9197                 let script_weight = match broadcast_alice {
9198                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9199                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9200                 };
9201                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9202                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9203                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9204                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9205                 if broadcast_alice && !go_onchain_before_fulfill {
9206                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9207                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9208                 } else {
9209                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9210                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9211                 }
9212         }
9213 }
9214
9215 #[test]
9216 fn test_onchain_htlc_settlement_after_close() {
9217         do_test_onchain_htlc_settlement_after_close(true, true);
9218         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9219         do_test_onchain_htlc_settlement_after_close(true, false);
9220         do_test_onchain_htlc_settlement_after_close(false, false);
9221 }
9222
9223 #[test]
9224 fn test_duplicate_chan_id() {
9225         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9226         // already open we reject it and keep the old channel.
9227         //
9228         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9229         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9230         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9231         // updating logic for the existing channel.
9232         let chanmon_cfgs = create_chanmon_cfgs(2);
9233         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9234         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9235         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9236
9237         // Create an initial channel
9238         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9239         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9240         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9241         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()));
9242
9243         // Try to create a second channel with the same temporary_channel_id as the first and check
9244         // that it is rejected.
9245         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9246         {
9247                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9248                 assert_eq!(events.len(), 1);
9249                 match events[0] {
9250                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9251                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9252                                 // first (valid) and second (invalid) channels are closed, given they both have
9253                                 // the same non-temporary channel_id. However, currently we do not, so we just
9254                                 // move forward with it.
9255                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9256                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9257                         },
9258                         _ => panic!("Unexpected event"),
9259                 }
9260         }
9261
9262         // Move the first channel through the funding flow...
9263         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9264
9265         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9266         check_added_monitors!(nodes[0], 0);
9267
9268         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9269         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9270         {
9271                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9272                 assert_eq!(added_monitors.len(), 1);
9273                 assert_eq!(added_monitors[0].0, funding_output);
9274                 added_monitors.clear();
9275         }
9276         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9277
9278         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9279         let channel_id = funding_outpoint.to_channel_id();
9280
9281         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9282         // temporary one).
9283
9284         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9285         // Technically this is allowed by the spec, but we don't support it and there's little reason
9286         // to. Still, it shouldn't cause any other issues.
9287         open_chan_msg.temporary_channel_id = channel_id;
9288         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9289         {
9290                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9291                 assert_eq!(events.len(), 1);
9292                 match events[0] {
9293                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9294                                 // Technically, at this point, nodes[1] would be justified in thinking both
9295                                 // channels are closed, but currently we do not, so we just move forward with it.
9296                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9297                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9298                         },
9299                         _ => panic!("Unexpected event"),
9300                 }
9301         }
9302
9303         // Now try to create a second channel which has a duplicate funding output.
9304         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9305         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9306         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9307         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()));
9308         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9309
9310         let funding_created = {
9311                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9312                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9313                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9314                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9315                 // channelmanager in a possibly nonsense state instead).
9316                 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9317                 let logger = test_utils::TestLogger::new();
9318                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9319         };
9320         check_added_monitors!(nodes[0], 0);
9321         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9322         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9323         // still needs to be cleared here.
9324         check_added_monitors!(nodes[1], 1);
9325
9326         // ...still, nodes[1] will reject the duplicate channel.
9327         {
9328                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9329                 assert_eq!(events.len(), 1);
9330                 match events[0] {
9331                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9332                                 // Technically, at this point, nodes[1] would be justified in thinking both
9333                                 // channels are closed, but currently we do not, so we just move forward with it.
9334                                 assert_eq!(msg.channel_id, channel_id);
9335                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9336                         },
9337                         _ => panic!("Unexpected event"),
9338                 }
9339         }
9340
9341         // finally, finish creating the original channel and send a payment over it to make sure
9342         // everything is functional.
9343         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9344         {
9345                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9346                 assert_eq!(added_monitors.len(), 1);
9347                 assert_eq!(added_monitors[0].0, funding_output);
9348                 added_monitors.clear();
9349         }
9350
9351         let events_4 = nodes[0].node.get_and_clear_pending_events();
9352         assert_eq!(events_4.len(), 0);
9353         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9354         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9355
9356         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9357         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9358         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9359         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9360 }
9361
9362 #[test]
9363 fn test_error_chans_closed() {
9364         // Test that we properly handle error messages, closing appropriate channels.
9365         //
9366         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9367         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9368         // we can test various edge cases around it to ensure we don't regress.
9369         let chanmon_cfgs = create_chanmon_cfgs(3);
9370         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9371         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9372         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9373
9374         // Create some initial channels
9375         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9376         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9377         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9378
9379         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9380         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9381         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9382
9383         // Closing a channel from a different peer has no effect
9384         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9385         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9386
9387         // Closing one channel doesn't impact others
9388         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9389         check_added_monitors!(nodes[0], 1);
9390         check_closed_broadcast!(nodes[0], false);
9391         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9392         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9393         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9394         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);
9395         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);
9396
9397         // A null channel ID should close all channels
9398         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9399         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9400         check_added_monitors!(nodes[0], 2);
9401         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9402         let events = nodes[0].node.get_and_clear_pending_msg_events();
9403         assert_eq!(events.len(), 2);
9404         match events[0] {
9405                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9406                         assert_eq!(msg.contents.flags & 2, 2);
9407                 },
9408                 _ => panic!("Unexpected event"),
9409         }
9410         match events[1] {
9411                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9412                         assert_eq!(msg.contents.flags & 2, 2);
9413                 },
9414                 _ => panic!("Unexpected event"),
9415         }
9416         // Note that at this point users of a standard PeerHandler will end up calling
9417         // peer_disconnected with no_connection_possible set to false, duplicating the
9418         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9419         // users with their own peer handling logic. We duplicate the call here, however.
9420         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9421         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9422
9423         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9424         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9425         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9426 }
9427
9428 #[test]
9429 fn test_invalid_funding_tx() {
9430         // Test that we properly handle invalid funding transactions sent to us from a peer.
9431         //
9432         // Previously, all other major lightning implementations had failed to properly sanitize
9433         // funding transactions from their counterparties, leading to a multi-implementation critical
9434         // security vulnerability (though we always sanitized properly, we've previously had
9435         // un-released crashes in the sanitization process).
9436         //
9437         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9438         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9439         // gave up on it. We test this here by generating such a transaction.
9440         let chanmon_cfgs = create_chanmon_cfgs(2);
9441         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9442         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9443         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9444
9445         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9446         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()));
9447         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()));
9448
9449         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9450
9451         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9452         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9453         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9454         // its length.
9455         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9456         assert!(chan_utils::HTLCType::scriptlen_to_htlctype(wit_program.len()).unwrap() ==
9457                 chan_utils::HTLCType::AcceptedHTLC);
9458
9459         let wit_program_script: Script = wit_program.clone().into();
9460         for output in tx.output.iter_mut() {
9461                 // Make the confirmed funding transaction have a bogus script_pubkey
9462                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9463         }
9464
9465         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9466         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()));
9467         check_added_monitors!(nodes[1], 1);
9468
9469         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()));
9470         check_added_monitors!(nodes[0], 1);
9471
9472         let events_1 = nodes[0].node.get_and_clear_pending_events();
9473         assert_eq!(events_1.len(), 0);
9474
9475         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9476         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9477         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9478
9479         let expected_err = "funding tx had wrong script/value or output index";
9480         confirm_transaction_at(&nodes[1], &tx, 1);
9481         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9482         check_added_monitors!(nodes[1], 1);
9483         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9484         assert_eq!(events_2.len(), 1);
9485         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9486                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9487                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9488                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9489                 } else { panic!(); }
9490         } else { panic!(); }
9491         assert_eq!(nodes[1].node.list_channels().len(), 0);
9492
9493         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9494         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9495         // as its not 32 bytes long.
9496         let mut spend_tx = Transaction {
9497                 version: 2i32, lock_time: 0,
9498                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9499                         previous_output: BitcoinOutPoint {
9500                                 txid: tx.txid(),
9501                                 vout: idx as u32,
9502                         },
9503                         script_sig: Script::new(),
9504                         sequence: 0xfffffffd,
9505                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9506                 }).collect(),
9507                 output: vec![TxOut {
9508                         value: 1000,
9509                         script_pubkey: Script::new(),
9510                 }]
9511         };
9512         check_spends!(spend_tx, tx);
9513         mine_transaction(&nodes[1], &spend_tx);
9514 }
9515
9516 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9517         // In the first version of the chain::Confirm interface, after a refactor was made to not
9518         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9519         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9520         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9521         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9522         // spending transaction until height N+1 (or greater). This was due to the way
9523         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9524         // spending transaction at the height the input transaction was confirmed at, not whether we
9525         // should broadcast a spending transaction at the current height.
9526         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9527         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9528         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9529         // until we learned about an additional block.
9530         //
9531         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9532         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9533         let chanmon_cfgs = create_chanmon_cfgs(3);
9534         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9535         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9536         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9537         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9538
9539         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9540         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9541         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9542         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9543         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9544
9545         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9546         check_closed_broadcast!(nodes[1], true);
9547         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9548         check_added_monitors!(nodes[1], 1);
9549         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9550         assert_eq!(node_txn.len(), 1);
9551
9552         let conf_height = nodes[1].best_block_info().1;
9553         if !test_height_before_timelock {
9554                 connect_blocks(&nodes[1], 24 * 6);
9555         }
9556         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9557                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9558         if test_height_before_timelock {
9559                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9560                 // generate any events or broadcast any transactions
9561                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9562                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9563         } else {
9564                 // We should broadcast an HTLC transaction spending our funding transaction first
9565                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9566                 assert_eq!(spending_txn.len(), 2);
9567                 assert_eq!(spending_txn[0], node_txn[0]);
9568                 check_spends!(spending_txn[1], node_txn[0]);
9569                 // We should also generate a SpendableOutputs event with the to_self output (as its
9570                 // timelock is up).
9571                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9572                 assert_eq!(descriptor_spend_txn.len(), 1);
9573
9574                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9575                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9576                 // additional block built on top of the current chain.
9577                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9578                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9579                 expect_pending_htlcs_forwardable!(nodes[1]);
9580                 check_added_monitors!(nodes[1], 1);
9581
9582                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9583                 assert!(updates.update_add_htlcs.is_empty());
9584                 assert!(updates.update_fulfill_htlcs.is_empty());
9585                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9586                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9587                 assert!(updates.update_fee.is_none());
9588                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9589                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9590                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9591         }
9592 }
9593
9594 #[test]
9595 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9596         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9597         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9598 }
9599
9600 #[test]
9601 fn test_forwardable_regen() {
9602         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9603         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9604         // HTLCs.
9605         // We test it for both payment receipt and payment forwarding.
9606
9607         let chanmon_cfgs = create_chanmon_cfgs(3);
9608         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9609         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9610         let persister: test_utils::TestPersister;
9611         let new_chain_monitor: test_utils::TestChainMonitor;
9612         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9613         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9614         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9615         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9616
9617         // First send a payment to nodes[1]
9618         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9619         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9620         check_added_monitors!(nodes[0], 1);
9621
9622         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9623         assert_eq!(events.len(), 1);
9624         let payment_event = SendEvent::from_event(events.pop().unwrap());
9625         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9626         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9627
9628         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9629
9630         // Next send a payment which is forwarded by nodes[1]
9631         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9632         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9633         check_added_monitors!(nodes[0], 1);
9634
9635         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9636         assert_eq!(events.len(), 1);
9637         let payment_event = SendEvent::from_event(events.pop().unwrap());
9638         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9639         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9640
9641         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9642         // generated
9643         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9644
9645         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9646         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9647         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9648
9649         let nodes_1_serialized = nodes[1].node.encode();
9650         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9651         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9652         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9653         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9654
9655         persister = test_utils::TestPersister::new();
9656         let keys_manager = &chanmon_cfgs[1].keys_manager;
9657         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);
9658         nodes[1].chain_monitor = &new_chain_monitor;
9659
9660         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9661         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9662                 &mut chan_0_monitor_read, keys_manager).unwrap();
9663         assert!(chan_0_monitor_read.is_empty());
9664         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9665         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9666                 &mut chan_1_monitor_read, keys_manager).unwrap();
9667         assert!(chan_1_monitor_read.is_empty());
9668
9669         let mut nodes_1_read = &nodes_1_serialized[..];
9670         let (_, nodes_1_deserialized_tmp) = {
9671                 let mut channel_monitors = HashMap::new();
9672                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9673                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9674                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9675                         default_config: UserConfig::default(),
9676                         keys_manager,
9677                         fee_estimator: node_cfgs[1].fee_estimator,
9678                         chain_monitor: nodes[1].chain_monitor,
9679                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9680                         logger: nodes[1].logger,
9681                         channel_monitors,
9682                 }).unwrap()
9683         };
9684         nodes_1_deserialized = nodes_1_deserialized_tmp;
9685         assert!(nodes_1_read.is_empty());
9686
9687         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9688         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9689         nodes[1].node = &nodes_1_deserialized;
9690         check_added_monitors!(nodes[1], 2);
9691
9692         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9693         // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9694         // the commitment state.
9695         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9696
9697         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9698
9699         expect_pending_htlcs_forwardable!(nodes[1]);
9700         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9701         check_added_monitors!(nodes[1], 1);
9702
9703         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9704         assert_eq!(events.len(), 1);
9705         let payment_event = SendEvent::from_event(events.pop().unwrap());
9706         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9707         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9708         expect_pending_htlcs_forwardable!(nodes[2]);
9709         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9710
9711         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9712         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9713 }
9714
9715 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9716         let chanmon_cfgs = create_chanmon_cfgs(2);
9717         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9718         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9719         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9720
9721         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9722
9723         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9724                 .with_features(InvoiceFeatures::known());
9725         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9726
9727         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9728
9729         {
9730                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9731                 check_added_monitors!(nodes[0], 1);
9732                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9733                 assert_eq!(events.len(), 1);
9734                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9735                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9736                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9737         }
9738         expect_pending_htlcs_forwardable!(nodes[1]);
9739         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9740
9741         {
9742                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9743                 check_added_monitors!(nodes[0], 1);
9744                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9745                 assert_eq!(events.len(), 1);
9746                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9747                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9748                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9749                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9750                 // assume the second is a privacy attack (no longer particularly relevant
9751                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9752                 // the first HTLC delivered above.
9753         }
9754
9755         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9756         nodes[1].node.process_pending_htlc_forwards();
9757
9758         if test_for_second_fail_panic {
9759                 // Now we go fail back the first HTLC from the user end.
9760                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9761
9762                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9763                 nodes[1].node.process_pending_htlc_forwards();
9764
9765                 check_added_monitors!(nodes[1], 1);
9766                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9767                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9768
9769                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9770                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9771                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9772
9773                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9774                 assert_eq!(failure_events.len(), 2);
9775                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9776                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9777         } else {
9778                 // Let the second HTLC fail and claim the first
9779                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9780                 nodes[1].node.process_pending_htlc_forwards();
9781
9782                 check_added_monitors!(nodes[1], 1);
9783                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9784                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9785                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9786
9787                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9788
9789                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9790         }
9791 }
9792
9793 #[test]
9794 fn test_dup_htlc_second_fail_panic() {
9795         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9796         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9797         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9798         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9799         do_test_dup_htlc_second_rejected(true);
9800 }
9801
9802 #[test]
9803 fn test_dup_htlc_second_rejected() {
9804         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9805         // simply reject the second HTLC but are still able to claim the first HTLC.
9806         do_test_dup_htlc_second_rejected(false);
9807 }
9808
9809 #[test]
9810 fn test_inconsistent_mpp_params() {
9811         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9812         // such HTLC and allow the second to stay.
9813         let chanmon_cfgs = create_chanmon_cfgs(4);
9814         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9815         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9816         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9817
9818         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9819         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9820         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9821         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9822
9823         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9824                 .with_features(InvoiceFeatures::known());
9825         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9826         assert_eq!(route.paths.len(), 2);
9827         route.paths.sort_by(|path_a, _| {
9828                 // Sort the path so that the path through nodes[1] comes first
9829                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9830                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9831         });
9832         let payment_params_opt = Some(payment_params);
9833
9834         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9835
9836         let cur_height = nodes[0].best_block_info().1;
9837         let payment_id = PaymentId([42; 32]);
9838         {
9839                 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();
9840                 check_added_monitors!(nodes[0], 1);
9841
9842                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9843                 assert_eq!(events.len(), 1);
9844                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9845         }
9846         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9847
9848         {
9849                 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();
9850                 check_added_monitors!(nodes[0], 1);
9851
9852                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9853                 assert_eq!(events.len(), 1);
9854                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9855
9856                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9857                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9858
9859                 expect_pending_htlcs_forwardable!(nodes[2]);
9860                 check_added_monitors!(nodes[2], 1);
9861
9862                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9863                 assert_eq!(events.len(), 1);
9864                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9865
9866                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9867                 check_added_monitors!(nodes[3], 0);
9868                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9869
9870                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9871                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9872                 // post-payment_secrets) and fail back the new HTLC.
9873         }
9874         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9875         nodes[3].node.process_pending_htlc_forwards();
9876         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9877         nodes[3].node.process_pending_htlc_forwards();
9878
9879         check_added_monitors!(nodes[3], 1);
9880
9881         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9882         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9883         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9884
9885         expect_pending_htlcs_forwardable!(nodes[2]);
9886         check_added_monitors!(nodes[2], 1);
9887
9888         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9889         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9890         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9891
9892         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9893
9894         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();
9895         check_added_monitors!(nodes[0], 1);
9896
9897         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9898         assert_eq!(events.len(), 1);
9899         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9900
9901         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9902 }
9903
9904 #[test]
9905 fn test_keysend_payments_to_public_node() {
9906         let chanmon_cfgs = create_chanmon_cfgs(2);
9907         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9908         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9909         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9910
9911         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9912         let network_graph = nodes[0].network_graph;
9913         let payer_pubkey = nodes[0].node.get_our_node_id();
9914         let payee_pubkey = nodes[1].node.get_our_node_id();
9915         let route_params = RouteParameters {
9916                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9917                 final_value_msat: 10000,
9918                 final_cltv_expiry_delta: 40,
9919         };
9920         let scorer = test_utils::TestScorer::with_penalty(0);
9921         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9922         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9923
9924         let test_preimage = PaymentPreimage([42; 32]);
9925         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9926         check_added_monitors!(nodes[0], 1);
9927         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9928         assert_eq!(events.len(), 1);
9929         let event = events.pop().unwrap();
9930         let path = vec![&nodes[1]];
9931         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9932         claim_payment(&nodes[0], &path, test_preimage);
9933 }
9934
9935 #[test]
9936 fn test_keysend_payments_to_private_node() {
9937         let chanmon_cfgs = create_chanmon_cfgs(2);
9938         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9939         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9940         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9941
9942         let payer_pubkey = nodes[0].node.get_our_node_id();
9943         let payee_pubkey = nodes[1].node.get_our_node_id();
9944         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9945         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9946
9947         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9948         let route_params = RouteParameters {
9949                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9950                 final_value_msat: 10000,
9951                 final_cltv_expiry_delta: 40,
9952         };
9953         let network_graph = nodes[0].network_graph;
9954         let first_hops = nodes[0].node.list_usable_channels();
9955         let scorer = test_utils::TestScorer::with_penalty(0);
9956         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9957         let route = find_route(
9958                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9959                 nodes[0].logger, &scorer, &random_seed_bytes
9960         ).unwrap();
9961
9962         let test_preimage = PaymentPreimage([42; 32]);
9963         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9964         check_added_monitors!(nodes[0], 1);
9965         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9966         assert_eq!(events.len(), 1);
9967         let event = events.pop().unwrap();
9968         let path = vec![&nodes[1]];
9969         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9970         claim_payment(&nodes[0], &path, test_preimage);
9971 }
9972
9973 #[test]
9974 fn test_double_partial_claim() {
9975         // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9976         // time out, the sender resends only some of the MPP parts, then the user processes the
9977         // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9978         // amount.
9979         let chanmon_cfgs = create_chanmon_cfgs(4);
9980         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9981         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9982         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9983
9984         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9985         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9986         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9987         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9988
9989         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9990         assert_eq!(route.paths.len(), 2);
9991         route.paths.sort_by(|path_a, _| {
9992                 // Sort the path so that the path through nodes[1] comes first
9993                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9994                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9995         });
9996
9997         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9998         // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
9999         // amount of time to respond to.
10000
10001         // Connect some blocks to time out the payment
10002         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
10003         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
10004
10005         expect_pending_htlcs_forwardable!(nodes[3]);
10006
10007         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
10008
10009         // nodes[1] now retries one of the two paths...
10010         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10011         check_added_monitors!(nodes[0], 2);
10012
10013         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10014         assert_eq!(events.len(), 2);
10015         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10016
10017         // At this point nodes[3] has received one half of the payment, and the user goes to handle
10018         // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
10019         nodes[3].node.claim_funds(payment_preimage);
10020         check_added_monitors!(nodes[3], 0);
10021         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
10022 }
10023
10024 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10025         // Test what happens if a node receives an MPP payment, claims it, but crashes before
10026         // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10027         // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10028         // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10029         // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10030         // not have the preimage tied to the still-pending HTLC.
10031         //
10032         // To get to the correct state, on startup we should propagate the preimage to the
10033         // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10034         // receiving the preimage without a state update.
10035         //
10036         // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10037         // definitely claimed.
10038         let chanmon_cfgs = create_chanmon_cfgs(4);
10039         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10040         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10041
10042         let persister: test_utils::TestPersister;
10043         let new_chain_monitor: test_utils::TestChainMonitor;
10044         let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10045
10046         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10047
10048         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10049         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10050         let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10051         let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10052
10053         // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10054         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10055         assert_eq!(route.paths.len(), 2);
10056         route.paths.sort_by(|path_a, _| {
10057                 // Sort the path so that the path through nodes[1] comes first
10058                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10059                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10060         });
10061
10062         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10063         check_added_monitors!(nodes[0], 2);
10064
10065         // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10066         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10067         assert_eq!(send_events.len(), 2);
10068         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);
10069         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);
10070
10071         // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10072         // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10073         let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10074         if !persist_both_monitors {
10075                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10076                         if outpoint.to_channel_id() == chan_id_not_persisted {
10077                                 assert!(original_monitor.0.is_empty());
10078                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10079                         }
10080                 }
10081         }
10082
10083         let mut original_manager = test_utils::TestVecWriter(Vec::new());
10084         nodes[3].node.write(&mut original_manager).unwrap();
10085
10086         expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10087
10088         nodes[3].node.claim_funds(payment_preimage);
10089         check_added_monitors!(nodes[3], 2);
10090         expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10091
10092         // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10093         // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10094         // with the old ChannelManager.
10095         let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10096         for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10097                 if outpoint.to_channel_id() == chan_id_persisted {
10098                         assert!(updated_monitor.0.is_empty());
10099                         nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10100                 }
10101         }
10102         // If `persist_both_monitors` is set, get the second monitor here as well
10103         if persist_both_monitors {
10104                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10105                         if outpoint.to_channel_id() == chan_id_not_persisted {
10106                                 assert!(original_monitor.0.is_empty());
10107                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10108                         }
10109                 }
10110         }
10111
10112         // Now restart nodes[3].
10113         persister = test_utils::TestPersister::new();
10114         let keys_manager = &chanmon_cfgs[3].keys_manager;
10115         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);
10116         nodes[3].chain_monitor = &new_chain_monitor;
10117         let mut monitors = Vec::new();
10118         for mut monitor_data in [original_monitor, updated_monitor].iter() {
10119                 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10120                 monitors.push(deserialized_monitor);
10121         }
10122
10123         let config = UserConfig::default();
10124         nodes_3_deserialized = {
10125                 let mut channel_monitors = HashMap::new();
10126                 for monitor in monitors.iter_mut() {
10127                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10128                 }
10129                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10130                         default_config: config,
10131                         keys_manager,
10132                         fee_estimator: node_cfgs[3].fee_estimator,
10133                         chain_monitor: nodes[3].chain_monitor,
10134                         tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10135                         logger: nodes[3].logger,
10136                         channel_monitors,
10137                 }).unwrap().1
10138         };
10139         nodes[3].node = &nodes_3_deserialized;
10140
10141         for monitor in monitors {
10142                 // On startup the preimage should have been copied into the non-persisted monitor:
10143                 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10144                 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10145         }
10146         check_added_monitors!(nodes[3], 2);
10147
10148         nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10149         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10150
10151         // During deserialization, we should have closed one channel and broadcast its latest
10152         // commitment transaction. We should also still have the original PaymentReceived event we
10153         // never finished processing.
10154         let events = nodes[3].node.get_and_clear_pending_events();
10155         assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10156         if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10157         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10158         if persist_both_monitors {
10159                 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10160         }
10161
10162         // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10163         // ChannelManager prior to handling the original one.
10164         if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10165                 events[if persist_both_monitors { 3 } else { 2 }]
10166         {
10167                 assert_eq!(payment_hash, our_payment_hash);
10168         } else { panic!(); }
10169
10170         assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10171         if !persist_both_monitors {
10172                 // If one of the two channels is still live, reveal the payment preimage over it.
10173
10174                 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10175                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10176                 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10177                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10178
10179                 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10180                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10181                 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10182
10183                 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10184
10185                 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10186                 // claim should fly.
10187                 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10188                 check_added_monitors!(nodes[3], 1);
10189                 assert_eq!(ds_msgs.len(), 2);
10190                 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10191
10192                 let cs_updates = match ds_msgs[0] {
10193                         MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10194                                 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10195                                 check_added_monitors!(nodes[2], 1);
10196                                 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10197                                 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10198                                 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10199                                 cs_updates
10200                         }
10201                         _ => panic!(),
10202                 };
10203
10204                 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10205                 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10206                 expect_payment_sent!(nodes[0], payment_preimage);
10207         }
10208 }
10209
10210 #[test]
10211 fn test_partial_claim_before_restart() {
10212         do_test_partial_claim_before_restart(false);
10213         do_test_partial_claim_before_restart(true);
10214 }
10215
10216 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10217 #[derive(Clone, Copy, PartialEq)]
10218 enum ExposureEvent {
10219         /// Breach occurs at HTLC forwarding (see `send_htlc`)
10220         AtHTLCForward,
10221         /// Breach occurs at HTLC reception (see `update_add_htlc`)
10222         AtHTLCReception,
10223         /// Breach occurs at outbound update_fee (see `send_update_fee`)
10224         AtUpdateFeeOutbound,
10225 }
10226
10227 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10228         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10229         // policy.
10230         //
10231         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10232         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10233         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10234         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10235         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10236         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10237         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10238         // might be available again for HTLC processing once the dust bandwidth has cleared up.
10239
10240         let chanmon_cfgs = create_chanmon_cfgs(2);
10241         let mut config = test_default_channel_config();
10242         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10243         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10244         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10245         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10246
10247         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10248         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10249         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10250         open_channel.max_accepted_htlcs = 60;
10251         if on_holder_tx {
10252                 open_channel.dust_limit_satoshis = 546;
10253         }
10254         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10255         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10256         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10257
10258         let opt_anchors = false;
10259
10260         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10261
10262         if on_holder_tx {
10263                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10264                         chan.holder_dust_limit_satoshis = 546;
10265                 }
10266         }
10267
10268         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10269         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()));
10270         check_added_monitors!(nodes[1], 1);
10271
10272         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()));
10273         check_added_monitors!(nodes[0], 1);
10274
10275         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10276         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10277         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10278
10279         let dust_buffer_feerate = {
10280                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10281                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10282                 chan.get_dust_buffer_feerate(None) as u64
10283         };
10284         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;
10285         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10286
10287         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;
10288         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10289
10290         let dust_htlc_on_counterparty_tx: u64 = 25;
10291         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10292
10293         if on_holder_tx {
10294                 if dust_outbound_balance {
10295                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10296                         // Outbound dust balance: 4372 sats
10297                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10298                         for i in 0..dust_outbound_htlc_on_holder_tx {
10299                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10300                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10301                         }
10302                 } else {
10303                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10304                         // Inbound dust balance: 4372 sats
10305                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10306                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10307                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10308                         }
10309                 }
10310         } else {
10311                 if dust_outbound_balance {
10312                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10313                         // Outbound dust balance: 5000 sats
10314                         for i in 0..dust_htlc_on_counterparty_tx {
10315                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10316                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10317                         }
10318                 } else {
10319                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10320                         // Inbound dust balance: 5000 sats
10321                         for _ in 0..dust_htlc_on_counterparty_tx {
10322                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10323                         }
10324                 }
10325         }
10326
10327         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10328         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10329                 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 });
10330                 let mut config = UserConfig::default();
10331                 // With default dust exposure: 5000 sats
10332                 if on_holder_tx {
10333                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10334                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10335                         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)));
10336                 } else {
10337                         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)));
10338                 }
10339         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10340                 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 });
10341                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10342                 check_added_monitors!(nodes[1], 1);
10343                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10344                 assert_eq!(events.len(), 1);
10345                 let payment_event = SendEvent::from_event(events.remove(0));
10346                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10347                 // With default dust exposure: 5000 sats
10348                 if on_holder_tx {
10349                         // Outbound dust balance: 6399 sats
10350                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10351                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10352                         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);
10353                 } else {
10354                         // Outbound dust balance: 5200 sats
10355                         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);
10356                 }
10357         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10358                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10359                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10360                 {
10361                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10362                         *feerate_lock = *feerate_lock * 10;
10363                 }
10364                 nodes[0].node.timer_tick_occurred();
10365                 check_added_monitors!(nodes[0], 1);
10366                 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);
10367         }
10368
10369         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10370         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10371         added_monitors.clear();
10372 }
10373
10374 #[test]
10375 fn test_max_dust_htlc_exposure() {
10376         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10377         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10378         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10379         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10380         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10381         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10382         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10383         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10384         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10385         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10386         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10387         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10388 }
10389
10390 #[test]
10391 fn test_non_final_funding_tx() {
10392         let chanmon_cfgs = create_chanmon_cfgs(2);
10393         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10394         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10395         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10396
10397         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10398         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10399         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
10400         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10401         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
10402
10403         let best_height = nodes[0].node.best_block.read().unwrap().height();
10404
10405         let chan_id = *nodes[0].network_chan_count.borrow();
10406         let events = nodes[0].node.get_and_clear_pending_events();
10407         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: 0x1, witness: Witness::from_vec(vec!(vec!(1))) };
10408         assert_eq!(events.len(), 1);
10409         let mut tx = match events[0] {
10410                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10411                         // Timelock the transaction _beyond_ the best client height + 2.
10412                         Transaction { version: chan_id as i32, lock_time: best_height + 3, input: vec![input], output: vec![TxOut {
10413                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10414                         }]}
10415                 },
10416                 _ => panic!("Unexpected event"),
10417         };
10418         // Transaction should fail as it's evaluated as non-final for propagation.
10419         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10420                 Err(APIError::APIMisuseError { err }) => {
10421                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10422                 },
10423                 _ => panic!()
10424         }
10425
10426         // However, transaction should be accepted if it's in a +2 headroom from best block.
10427         tx.lock_time -= 1;
10428         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10429         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10430 }