54817f35d7bea17ac0f13e5250220c4958e49a71
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use chain;
15 use chain::{Confirm, Listen, Watch};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{BaseSign, KeysInterface};
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS };
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
26 use routing::gossip::NetworkGraph;
27 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
28 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
29 use ln::msgs;
30 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, OptionalField, ErrorAction};
31 use util::enforcing_trait_impls::EnforcingSigner;
32 use util::{byte_utils, test_utils};
33 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
34 use util::errors::APIError;
35 use util::ser::{Writeable, ReadableArgs};
36 use util::config::UserConfig;
37
38 use bitcoin::hash_types::BlockHash;
39 use bitcoin::blockdata::block::{Block, BlockHeader};
40 use bitcoin::blockdata::script::Builder;
41 use bitcoin::blockdata::opcodes;
42 use bitcoin::blockdata::constants::genesis_block;
43 use bitcoin::network::constants::Network;
44 use bitcoin::{Transaction, TxIn, TxOut, Witness};
45 use bitcoin::OutPoint as BitcoinOutPoint;
46
47 use bitcoin::secp256k1::Secp256k1;
48 use bitcoin::secp256k1::{PublicKey,SecretKey};
49
50 use regex;
51
52 use io;
53 use prelude::*;
54 use alloc::collections::BTreeSet;
55 use core::default::Default;
56 use sync::{Arc, Mutex};
57
58 use ln::functional_test_utils::*;
59 use ln::chan_utils::CommitmentTransaction;
60
61 #[test]
62 fn test_insane_channel_opens() {
63         // Stand up a network of 2 nodes
64         use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
65         let mut cfg = UserConfig::default();
66         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
67         let chanmon_cfgs = create_chanmon_cfgs(2);
68         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
69         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
70         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
71
72         // Instantiate channel parameters where we push the maximum msats given our
73         // funding satoshis
74         let channel_value_sat = 31337; // same as funding satoshis
75         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
76         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
77
78         // Have node0 initiate a channel to node1 with aforementioned parameters
79         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
80
81         // Extract the channel open message from node0 to node1
82         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
83
84         // Test helper that asserts we get the correct error string given a mutator
85         // that supposedly makes the channel open message insane
86         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
87                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
88                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
89                 assert_eq!(msg_events.len(), 1);
90                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
91                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
92                         match action {
93                                 &ErrorAction::SendErrorMessage { .. } => {
94                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
95                                 },
96                                 _ => panic!("unexpected event!"),
97                         }
98                 } else { assert!(false); }
99         };
100
101         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
102
103         // Test all mutations that would make the channel open message insane
104         insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
105         insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
106
107         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
108
109         insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
110
111         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
112
113         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
114
115         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
116
117         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
118
119         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
120 }
121
122 #[test]
123 fn test_funding_exceeds_no_wumbo_limit() {
124         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
125         // them.
126         use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
127         let chanmon_cfgs = create_chanmon_cfgs(2);
128         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
129         node_cfgs[1].features = InitFeatures::known().clear_wumbo();
130         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
131         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
132
133         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
134                 Err(APIError::APIMisuseError { err }) => {
135                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
136                 },
137                 _ => panic!()
138         }
139 }
140
141 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
142         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
143         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
144         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
145         // in normal testing, we test it explicitly here.
146         let chanmon_cfgs = create_chanmon_cfgs(2);
147         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
148         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
149         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
150
151         // Have node0 initiate a channel to node1 with aforementioned parameters
152         let mut push_amt = 100_000_000;
153         let feerate_per_kw = 253;
154         let opt_anchors = false;
155         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
156         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
157
158         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
159         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
160         if !send_from_initiator {
161                 open_channel_message.channel_reserve_satoshis = 0;
162                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
163         }
164         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
165
166         // Extract the channel accept message from node1 to node0
167         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
168         if send_from_initiator {
169                 accept_channel_message.channel_reserve_satoshis = 0;
170                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
171         }
172         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
173         {
174                 let mut lock;
175                 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
176                 chan.holder_selected_channel_reserve_satoshis = 0;
177                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
178         }
179
180         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
181         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
182         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
183
184         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
185         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
186         if send_from_initiator {
187                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
188                         // Note that for outbound channels we have to consider the commitment tx fee and the
189                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
190                         // well as an additional HTLC.
191                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
192         } else {
193                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
194         }
195 }
196
197 #[test]
198 fn test_counterparty_no_reserve() {
199         do_test_counterparty_no_reserve(true);
200         do_test_counterparty_no_reserve(false);
201 }
202
203 #[test]
204 fn test_async_inbound_update_fee() {
205         let chanmon_cfgs = create_chanmon_cfgs(2);
206         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
207         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
208         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
209         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
210
211         // balancing
212         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
213
214         // A                                        B
215         // update_fee                            ->
216         // send (1) commitment_signed            -.
217         //                                       <- update_add_htlc/commitment_signed
218         // send (2) RAA (awaiting remote revoke) -.
219         // (1) commitment_signed is delivered    ->
220         //                                       .- send (3) RAA (awaiting remote revoke)
221         // (2) RAA is delivered                  ->
222         //                                       .- send (4) commitment_signed
223         //                                       <- (3) RAA is delivered
224         // send (5) commitment_signed            -.
225         //                                       <- (4) commitment_signed is delivered
226         // send (6) RAA                          -.
227         // (5) commitment_signed is delivered    ->
228         //                                       <- RAA
229         // (6) RAA is delivered                  ->
230
231         // First nodes[0] generates an update_fee
232         {
233                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
234                 *feerate_lock += 20;
235         }
236         nodes[0].node.timer_tick_occurred();
237         check_added_monitors!(nodes[0], 1);
238
239         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
240         assert_eq!(events_0.len(), 1);
241         let (update_msg, commitment_signed) = match events_0[0] { // (1)
242                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
243                         (update_fee.as_ref(), commitment_signed)
244                 },
245                 _ => panic!("Unexpected event"),
246         };
247
248         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
249
250         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
251         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
252         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
253         check_added_monitors!(nodes[1], 1);
254
255         let payment_event = {
256                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
257                 assert_eq!(events_1.len(), 1);
258                 SendEvent::from_event(events_1.remove(0))
259         };
260         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
261         assert_eq!(payment_event.msgs.len(), 1);
262
263         // ...now when the messages get delivered everyone should be happy
264         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
265         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
266         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
267         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
268         check_added_monitors!(nodes[0], 1);
269
270         // deliver(1), generate (3):
271         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
272         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
273         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
274         check_added_monitors!(nodes[1], 1);
275
276         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
277         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
278         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
279         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
280         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
281         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
282         assert!(bs_update.update_fee.is_none()); // (4)
283         check_added_monitors!(nodes[1], 1);
284
285         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
286         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
287         assert!(as_update.update_add_htlcs.is_empty()); // (5)
288         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
289         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
290         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
291         assert!(as_update.update_fee.is_none()); // (5)
292         check_added_monitors!(nodes[0], 1);
293
294         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
295         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
296         // only (6) so get_event_msg's assert(len == 1) passes
297         check_added_monitors!(nodes[0], 1);
298
299         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
300         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
301         check_added_monitors!(nodes[1], 1);
302
303         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
304         check_added_monitors!(nodes[0], 1);
305
306         let events_2 = nodes[0].node.get_and_clear_pending_events();
307         assert_eq!(events_2.len(), 1);
308         match events_2[0] {
309                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
310                 _ => panic!("Unexpected event"),
311         }
312
313         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
314         check_added_monitors!(nodes[1], 1);
315 }
316
317 #[test]
318 fn test_update_fee_unordered_raa() {
319         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
320         // crash in an earlier version of the update_fee patch)
321         let chanmon_cfgs = create_chanmon_cfgs(2);
322         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
323         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
324         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
325         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
326
327         // balancing
328         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
329
330         // First nodes[0] generates an update_fee
331         {
332                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
333                 *feerate_lock += 20;
334         }
335         nodes[0].node.timer_tick_occurred();
336         check_added_monitors!(nodes[0], 1);
337
338         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
339         assert_eq!(events_0.len(), 1);
340         let update_msg = match events_0[0] { // (1)
341                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
342                         update_fee.as_ref()
343                 },
344                 _ => panic!("Unexpected event"),
345         };
346
347         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
348
349         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
350         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
351         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
352         check_added_monitors!(nodes[1], 1);
353
354         let payment_event = {
355                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
356                 assert_eq!(events_1.len(), 1);
357                 SendEvent::from_event(events_1.remove(0))
358         };
359         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
360         assert_eq!(payment_event.msgs.len(), 1);
361
362         // ...now when the messages get delivered everyone should be happy
363         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
364         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
365         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
366         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
367         check_added_monitors!(nodes[0], 1);
368
369         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
370         check_added_monitors!(nodes[1], 1);
371
372         // We can't continue, sadly, because our (1) now has a bogus signature
373 }
374
375 #[test]
376 fn test_multi_flight_update_fee() {
377         let chanmon_cfgs = create_chanmon_cfgs(2);
378         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
379         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
380         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
381         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
382
383         // A                                        B
384         // update_fee/commitment_signed          ->
385         //                                       .- send (1) RAA and (2) commitment_signed
386         // update_fee (never committed)          ->
387         // (3) update_fee                        ->
388         // We have to manually generate the above update_fee, it is allowed by the protocol but we
389         // don't track which updates correspond to which revoke_and_ack responses so we're in
390         // AwaitingRAA mode and will not generate the update_fee yet.
391         //                                       <- (1) RAA delivered
392         // (3) is generated and send (4) CS      -.
393         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
394         // know the per_commitment_point to use for it.
395         //                                       <- (2) commitment_signed delivered
396         // revoke_and_ack                        ->
397         //                                          B should send no response here
398         // (4) commitment_signed delivered       ->
399         //                                       <- RAA/commitment_signed delivered
400         // revoke_and_ack                        ->
401
402         // First nodes[0] generates an update_fee
403         let initial_feerate;
404         {
405                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
406                 initial_feerate = *feerate_lock;
407                 *feerate_lock = initial_feerate + 20;
408         }
409         nodes[0].node.timer_tick_occurred();
410         check_added_monitors!(nodes[0], 1);
411
412         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
413         assert_eq!(events_0.len(), 1);
414         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
415                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
416                         (update_fee.as_ref().unwrap(), commitment_signed)
417                 },
418                 _ => panic!("Unexpected event"),
419         };
420
421         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
422         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
423         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
424         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
425         check_added_monitors!(nodes[1], 1);
426
427         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
428         // transaction:
429         {
430                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
431                 *feerate_lock = initial_feerate + 40;
432         }
433         nodes[0].node.timer_tick_occurred();
434         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
435         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
436
437         // Create the (3) update_fee message that nodes[0] will generate before it does...
438         let mut update_msg_2 = msgs::UpdateFee {
439                 channel_id: update_msg_1.channel_id.clone(),
440                 feerate_per_kw: (initial_feerate + 30) as u32,
441         };
442
443         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
444
445         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
446         // Deliver (3)
447         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
448
449         // Deliver (1), generating (3) and (4)
450         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
451         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
452         check_added_monitors!(nodes[0], 1);
453         assert!(as_second_update.update_add_htlcs.is_empty());
454         assert!(as_second_update.update_fulfill_htlcs.is_empty());
455         assert!(as_second_update.update_fail_htlcs.is_empty());
456         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
457         // Check that the update_fee newly generated matches what we delivered:
458         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
459         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
460
461         // Deliver (2) commitment_signed
462         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
463         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
464         check_added_monitors!(nodes[0], 1);
465         // No commitment_signed so get_event_msg's assert(len == 1) passes
466
467         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
468         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
469         check_added_monitors!(nodes[1], 1);
470
471         // Delever (4)
472         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
473         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
474         check_added_monitors!(nodes[1], 1);
475
476         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
477         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
478         check_added_monitors!(nodes[0], 1);
479
480         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
481         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
482         // No commitment_signed so get_event_msg's assert(len == 1) passes
483         check_added_monitors!(nodes[0], 1);
484
485         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
486         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
487         check_added_monitors!(nodes[1], 1);
488 }
489
490 fn do_test_sanity_on_in_flight_opens(steps: u8) {
491         // Previously, we had issues deserializing channels when we hadn't connected the first block
492         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
493         // serialization round-trips and simply do steps towards opening a channel and then drop the
494         // Node objects.
495
496         let chanmon_cfgs = create_chanmon_cfgs(2);
497         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
498         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
499         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
500
501         if steps & 0b1000_0000 != 0{
502                 let block = Block {
503                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
504                         txdata: vec![],
505                 };
506                 connect_block(&nodes[0], &block);
507                 connect_block(&nodes[1], &block);
508         }
509
510         if steps & 0x0f == 0 { return; }
511         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
512         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
513
514         if steps & 0x0f == 1 { return; }
515         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
516         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
517
518         if steps & 0x0f == 2 { return; }
519         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
520
521         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
522
523         if steps & 0x0f == 3 { return; }
524         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
525         check_added_monitors!(nodes[0], 0);
526         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
527
528         if steps & 0x0f == 4 { return; }
529         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
530         {
531                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
532                 assert_eq!(added_monitors.len(), 1);
533                 assert_eq!(added_monitors[0].0, funding_output);
534                 added_monitors.clear();
535         }
536         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
537
538         if steps & 0x0f == 5 { return; }
539         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
540         {
541                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
542                 assert_eq!(added_monitors.len(), 1);
543                 assert_eq!(added_monitors[0].0, funding_output);
544                 added_monitors.clear();
545         }
546
547         let events_4 = nodes[0].node.get_and_clear_pending_events();
548         assert_eq!(events_4.len(), 0);
549
550         if steps & 0x0f == 6 { return; }
551         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
552
553         if steps & 0x0f == 7 { return; }
554         confirm_transaction_at(&nodes[0], &tx, 2);
555         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
556         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
557 }
558
559 #[test]
560 fn test_sanity_on_in_flight_opens() {
561         do_test_sanity_on_in_flight_opens(0);
562         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
563         do_test_sanity_on_in_flight_opens(1);
564         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
565         do_test_sanity_on_in_flight_opens(2);
566         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
567         do_test_sanity_on_in_flight_opens(3);
568         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
569         do_test_sanity_on_in_flight_opens(4);
570         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
571         do_test_sanity_on_in_flight_opens(5);
572         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
573         do_test_sanity_on_in_flight_opens(6);
574         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
575         do_test_sanity_on_in_flight_opens(7);
576         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
577         do_test_sanity_on_in_flight_opens(8);
578         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
579 }
580
581 #[test]
582 fn test_update_fee_vanilla() {
583         let chanmon_cfgs = create_chanmon_cfgs(2);
584         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
585         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
586         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
587         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
588
589         {
590                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
591                 *feerate_lock += 25;
592         }
593         nodes[0].node.timer_tick_occurred();
594         check_added_monitors!(nodes[0], 1);
595
596         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
597         assert_eq!(events_0.len(), 1);
598         let (update_msg, commitment_signed) = match events_0[0] {
599                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
600                         (update_fee.as_ref(), commitment_signed)
601                 },
602                 _ => panic!("Unexpected event"),
603         };
604         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
605
606         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
607         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
608         check_added_monitors!(nodes[1], 1);
609
610         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
611         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
612         check_added_monitors!(nodes[0], 1);
613
614         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
615         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
616         // No commitment_signed so get_event_msg's assert(len == 1) passes
617         check_added_monitors!(nodes[0], 1);
618
619         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
620         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
621         check_added_monitors!(nodes[1], 1);
622 }
623
624 #[test]
625 fn test_update_fee_that_funder_cannot_afford() {
626         let chanmon_cfgs = create_chanmon_cfgs(2);
627         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
628         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
629         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
630         let channel_value = 5000;
631         let push_sats = 700;
632         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
633         let channel_id = chan.2;
634         let secp_ctx = Secp256k1::new();
635         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
636
637         let opt_anchors = false;
638
639         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
640         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
641         // calculate two different feerates here - the expected local limit as well as the expected
642         // remote limit.
643         let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
644         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
645         {
646                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
647                 *feerate_lock = feerate;
648         }
649         nodes[0].node.timer_tick_occurred();
650         check_added_monitors!(nodes[0], 1);
651         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
652
653         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
654
655         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
656
657         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
658         {
659                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
660
661                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
662                 assert_eq!(commitment_tx.output.len(), 2);
663                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
664                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
665                 actual_fee = channel_value - actual_fee;
666                 assert_eq!(total_fee, actual_fee);
667         }
668
669         {
670                 // Increment the feerate by a small constant, accounting for rounding errors
671                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
672                 *feerate_lock += 4;
673         }
674         nodes[0].node.timer_tick_occurred();
675         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
676         check_added_monitors!(nodes[0], 0);
677
678         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
679
680         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
681         // needed to sign the new commitment tx and (2) sign the new commitment tx.
682         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
683                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
684                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
685                 let chan_signer = local_chan.get_signer();
686                 let pubkeys = chan_signer.pubkeys();
687                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
688                  pubkeys.funding_pubkey)
689         };
690         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
691                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
692                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
693                 let chan_signer = remote_chan.get_signer();
694                 let pubkeys = chan_signer.pubkeys();
695                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
696                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
697                  pubkeys.funding_pubkey)
698         };
699
700         // Assemble the set of keys we can use for signatures for our commitment_signed message.
701         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
702                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
703
704         let res = {
705                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
706                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
707                 let local_chan_signer = local_chan.get_signer();
708                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
709                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
710                         INITIAL_COMMITMENT_NUMBER - 1,
711                         push_sats,
712                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
713                         opt_anchors, local_funding, remote_funding,
714                         commit_tx_keys.clone(),
715                         non_buffer_feerate + 4,
716                         &mut htlcs,
717                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
718                 );
719                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
720         };
721
722         let commit_signed_msg = msgs::CommitmentSigned {
723                 channel_id: chan.2,
724                 signature: res.0,
725                 htlc_signatures: res.1
726         };
727
728         let update_fee = msgs::UpdateFee {
729                 channel_id: chan.2,
730                 feerate_per_kw: non_buffer_feerate + 4,
731         };
732
733         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
734
735         //While producing the commitment_signed response after handling a received update_fee request the
736         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
737         //Should produce and error.
738         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
739         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
740         check_added_monitors!(nodes[1], 1);
741         check_closed_broadcast!(nodes[1], true);
742         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
743 }
744
745 #[test]
746 fn test_update_fee_with_fundee_update_add_htlc() {
747         let chanmon_cfgs = create_chanmon_cfgs(2);
748         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
749         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
750         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
751         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
752
753         // balancing
754         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
755
756         {
757                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
758                 *feerate_lock += 20;
759         }
760         nodes[0].node.timer_tick_occurred();
761         check_added_monitors!(nodes[0], 1);
762
763         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
764         assert_eq!(events_0.len(), 1);
765         let (update_msg, commitment_signed) = match events_0[0] {
766                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
767                         (update_fee.as_ref(), commitment_signed)
768                 },
769                 _ => panic!("Unexpected event"),
770         };
771         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
772         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
773         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
774         check_added_monitors!(nodes[1], 1);
775
776         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
777
778         // nothing happens since node[1] is in AwaitingRemoteRevoke
779         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
780         {
781                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
782                 assert_eq!(added_monitors.len(), 0);
783                 added_monitors.clear();
784         }
785         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
786         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
787         // node[1] has nothing to do
788
789         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
790         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
791         check_added_monitors!(nodes[0], 1);
792
793         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
794         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
795         // No commitment_signed so get_event_msg's assert(len == 1) passes
796         check_added_monitors!(nodes[0], 1);
797         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
798         check_added_monitors!(nodes[1], 1);
799         // AwaitingRemoteRevoke ends here
800
801         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
802         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
803         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
804         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
805         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
806         assert_eq!(commitment_update.update_fee.is_none(), true);
807
808         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
809         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
810         check_added_monitors!(nodes[0], 1);
811         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
812
813         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
814         check_added_monitors!(nodes[1], 1);
815         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
816
817         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
818         check_added_monitors!(nodes[1], 1);
819         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
820         // No commitment_signed so get_event_msg's assert(len == 1) passes
821
822         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
823         check_added_monitors!(nodes[0], 1);
824         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
825
826         expect_pending_htlcs_forwardable!(nodes[0]);
827
828         let events = nodes[0].node.get_and_clear_pending_events();
829         assert_eq!(events.len(), 1);
830         match events[0] {
831                 Event::PaymentReceived { .. } => { },
832                 _ => panic!("Unexpected event"),
833         };
834
835         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
836
837         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
838         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
839         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
840         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
841         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
842 }
843
844 #[test]
845 fn test_update_fee() {
846         let chanmon_cfgs = create_chanmon_cfgs(2);
847         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
848         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
849         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
850         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
851         let channel_id = chan.2;
852
853         // A                                        B
854         // (1) update_fee/commitment_signed      ->
855         //                                       <- (2) revoke_and_ack
856         //                                       .- send (3) commitment_signed
857         // (4) update_fee/commitment_signed      ->
858         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
859         //                                       <- (3) commitment_signed delivered
860         // send (6) revoke_and_ack               -.
861         //                                       <- (5) deliver revoke_and_ack
862         // (6) deliver revoke_and_ack            ->
863         //                                       .- send (7) commitment_signed in response to (4)
864         //                                       <- (7) deliver commitment_signed
865         // revoke_and_ack                        ->
866
867         // Create and deliver (1)...
868         let feerate;
869         {
870                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
871                 feerate = *feerate_lock;
872                 *feerate_lock = feerate + 20;
873         }
874         nodes[0].node.timer_tick_occurred();
875         check_added_monitors!(nodes[0], 1);
876
877         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
878         assert_eq!(events_0.len(), 1);
879         let (update_msg, commitment_signed) = match events_0[0] {
880                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
881                         (update_fee.as_ref(), commitment_signed)
882                 },
883                 _ => panic!("Unexpected event"),
884         };
885         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
886
887         // Generate (2) and (3):
888         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
889         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
890         check_added_monitors!(nodes[1], 1);
891
892         // Deliver (2):
893         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
894         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
895         check_added_monitors!(nodes[0], 1);
896
897         // Create and deliver (4)...
898         {
899                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
900                 *feerate_lock = feerate + 30;
901         }
902         nodes[0].node.timer_tick_occurred();
903         check_added_monitors!(nodes[0], 1);
904         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
905         assert_eq!(events_0.len(), 1);
906         let (update_msg, commitment_signed) = match events_0[0] {
907                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
908                         (update_fee.as_ref(), commitment_signed)
909                 },
910                 _ => panic!("Unexpected event"),
911         };
912
913         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
914         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
915         check_added_monitors!(nodes[1], 1);
916         // ... creating (5)
917         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
918         // No commitment_signed so get_event_msg's assert(len == 1) passes
919
920         // Handle (3), creating (6):
921         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
922         check_added_monitors!(nodes[0], 1);
923         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
924         // No commitment_signed so get_event_msg's assert(len == 1) passes
925
926         // Deliver (5):
927         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
928         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
929         check_added_monitors!(nodes[0], 1);
930
931         // Deliver (6), creating (7):
932         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
933         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
934         assert!(commitment_update.update_add_htlcs.is_empty());
935         assert!(commitment_update.update_fulfill_htlcs.is_empty());
936         assert!(commitment_update.update_fail_htlcs.is_empty());
937         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
938         assert!(commitment_update.update_fee.is_none());
939         check_added_monitors!(nodes[1], 1);
940
941         // Deliver (7)
942         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
943         check_added_monitors!(nodes[0], 1);
944         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
945         // No commitment_signed so get_event_msg's assert(len == 1) passes
946
947         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
948         check_added_monitors!(nodes[1], 1);
949         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
950
951         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
952         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
953         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
954         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
955         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
956 }
957
958 #[test]
959 fn fake_network_test() {
960         // Simple test which builds a network of ChannelManagers, connects them to each other, and
961         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
962         let chanmon_cfgs = create_chanmon_cfgs(4);
963         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
964         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
965         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
966
967         // Create some initial channels
968         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
969         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
970         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
971
972         // Rebalance the network a bit by relaying one payment through all the channels...
973         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
974         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
975         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
976         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
977
978         // Send some more payments
979         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
980         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
981         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
982
983         // Test failure packets
984         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
985         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
986
987         // Add a new channel that skips 3
988         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
989
990         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
991         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
992         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
993         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
994         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
995         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
996         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
997
998         // Do some rebalance loop payments, simultaneously
999         let mut hops = Vec::with_capacity(3);
1000         hops.push(RouteHop {
1001                 pubkey: nodes[2].node.get_our_node_id(),
1002                 node_features: NodeFeatures::empty(),
1003                 short_channel_id: chan_2.0.contents.short_channel_id,
1004                 channel_features: ChannelFeatures::empty(),
1005                 fee_msat: 0,
1006                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1007         });
1008         hops.push(RouteHop {
1009                 pubkey: nodes[3].node.get_our_node_id(),
1010                 node_features: NodeFeatures::empty(),
1011                 short_channel_id: chan_3.0.contents.short_channel_id,
1012                 channel_features: ChannelFeatures::empty(),
1013                 fee_msat: 0,
1014                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1015         });
1016         hops.push(RouteHop {
1017                 pubkey: nodes[1].node.get_our_node_id(),
1018                 node_features: NodeFeatures::known(),
1019                 short_channel_id: chan_4.0.contents.short_channel_id,
1020                 channel_features: ChannelFeatures::known(),
1021                 fee_msat: 1000000,
1022                 cltv_expiry_delta: TEST_FINAL_CLTV,
1023         });
1024         hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1025         hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1026         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1027
1028         let mut hops = Vec::with_capacity(3);
1029         hops.push(RouteHop {
1030                 pubkey: nodes[3].node.get_our_node_id(),
1031                 node_features: NodeFeatures::empty(),
1032                 short_channel_id: chan_4.0.contents.short_channel_id,
1033                 channel_features: ChannelFeatures::empty(),
1034                 fee_msat: 0,
1035                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1036         });
1037         hops.push(RouteHop {
1038                 pubkey: nodes[2].node.get_our_node_id(),
1039                 node_features: NodeFeatures::empty(),
1040                 short_channel_id: chan_3.0.contents.short_channel_id,
1041                 channel_features: ChannelFeatures::empty(),
1042                 fee_msat: 0,
1043                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1044         });
1045         hops.push(RouteHop {
1046                 pubkey: nodes[1].node.get_our_node_id(),
1047                 node_features: NodeFeatures::known(),
1048                 short_channel_id: chan_2.0.contents.short_channel_id,
1049                 channel_features: ChannelFeatures::known(),
1050                 fee_msat: 1000000,
1051                 cltv_expiry_delta: TEST_FINAL_CLTV,
1052         });
1053         hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1054         hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1055         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1056
1057         // Claim the rebalances...
1058         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1059         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1060
1061         // Add a duplicate new channel from 2 to 4
1062         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1063
1064         // Send some payments across both channels
1065         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1066         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1067         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1068
1069
1070         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1071         let events = nodes[0].node.get_and_clear_pending_msg_events();
1072         assert_eq!(events.len(), 0);
1073         nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1074
1075         //TODO: Test that routes work again here as we've been notified that the channel is full
1076
1077         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1078         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1079         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1080
1081         // Close down the channels...
1082         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1083         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1084         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1085         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1086         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1087         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1088         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1089         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1090         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1091         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1092         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1093         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1094         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1095         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1096         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1097 }
1098
1099 #[test]
1100 fn holding_cell_htlc_counting() {
1101         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1102         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1103         // commitment dance rounds.
1104         let chanmon_cfgs = create_chanmon_cfgs(3);
1105         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1106         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1107         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1108         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1109         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1110
1111         let mut payments = Vec::new();
1112         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1113                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1114                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1115                 payments.push((payment_preimage, payment_hash));
1116         }
1117         check_added_monitors!(nodes[1], 1);
1118
1119         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1120         assert_eq!(events.len(), 1);
1121         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1122         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1123
1124         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1125         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1126         // another HTLC.
1127         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1128         {
1129                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1130                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1131                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1132                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1133         }
1134
1135         // This should also be true if we try to forward a payment.
1136         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1137         {
1138                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1139                 check_added_monitors!(nodes[0], 1);
1140         }
1141
1142         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1143         assert_eq!(events.len(), 1);
1144         let payment_event = SendEvent::from_event(events.pop().unwrap());
1145         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1146
1147         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1148         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1149         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1150         // fails), the second will process the resulting failure and fail the HTLC backward.
1151         expect_pending_htlcs_forwardable!(nodes[1]);
1152         expect_pending_htlcs_forwardable!(nodes[1]);
1153         check_added_monitors!(nodes[1], 1);
1154
1155         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1156         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1157         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1158
1159         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1160
1161         // Now forward all the pending HTLCs and claim them back
1162         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1163         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1164         check_added_monitors!(nodes[2], 1);
1165
1166         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1167         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1168         check_added_monitors!(nodes[1], 1);
1169         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1170
1171         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1172         check_added_monitors!(nodes[1], 1);
1173         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1174
1175         for ref update in as_updates.update_add_htlcs.iter() {
1176                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1177         }
1178         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1179         check_added_monitors!(nodes[2], 1);
1180         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1181         check_added_monitors!(nodes[2], 1);
1182         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1183
1184         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1185         check_added_monitors!(nodes[1], 1);
1186         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1187         check_added_monitors!(nodes[1], 1);
1188         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1189
1190         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1191         check_added_monitors!(nodes[2], 1);
1192
1193         expect_pending_htlcs_forwardable!(nodes[2]);
1194
1195         let events = nodes[2].node.get_and_clear_pending_events();
1196         assert_eq!(events.len(), payments.len());
1197         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1198                 match event {
1199                         &Event::PaymentReceived { ref payment_hash, .. } => {
1200                                 assert_eq!(*payment_hash, *hash);
1201                         },
1202                         _ => panic!("Unexpected event"),
1203                 };
1204         }
1205
1206         for (preimage, _) in payments.drain(..) {
1207                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1208         }
1209
1210         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1211 }
1212
1213 #[test]
1214 fn duplicate_htlc_test() {
1215         // Test that we accept duplicate payment_hash HTLCs across the network and that
1216         // claiming/failing them are all separate and don't affect each other
1217         let chanmon_cfgs = create_chanmon_cfgs(6);
1218         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1219         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1220         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1221
1222         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1223         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1224         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1225         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1226         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1227         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1228
1229         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1230
1231         *nodes[0].network_payment_count.borrow_mut() -= 1;
1232         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1233
1234         *nodes[0].network_payment_count.borrow_mut() -= 1;
1235         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1236
1237         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1238         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1239         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1240 }
1241
1242 #[test]
1243 fn test_duplicate_htlc_different_direction_onchain() {
1244         // Test that ChannelMonitor doesn't generate 2 preimage txn
1245         // when we have 2 HTLCs with same preimage that go across a node
1246         // in opposite directions, even with the same payment secret.
1247         let chanmon_cfgs = create_chanmon_cfgs(2);
1248         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1249         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1250         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1251
1252         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1253
1254         // balancing
1255         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1256
1257         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1258
1259         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1260         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1261         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1262
1263         // Provide preimage to node 0 by claiming payment
1264         nodes[0].node.claim_funds(payment_preimage);
1265         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1266         check_added_monitors!(nodes[0], 1);
1267
1268         // Broadcast node 1 commitment txn
1269         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1270
1271         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1272         let mut has_both_htlcs = 0; // check htlcs match ones committed
1273         for outp in remote_txn[0].output.iter() {
1274                 if outp.value == 800_000 / 1000 {
1275                         has_both_htlcs += 1;
1276                 } else if outp.value == 900_000 / 1000 {
1277                         has_both_htlcs += 1;
1278                 }
1279         }
1280         assert_eq!(has_both_htlcs, 2);
1281
1282         mine_transaction(&nodes[0], &remote_txn[0]);
1283         check_added_monitors!(nodes[0], 1);
1284         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1285         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1286
1287         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1288         assert_eq!(claim_txn.len(), 8);
1289
1290         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1291
1292         check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1293         check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1294
1295         let bump_tx = if claim_txn[1] == claim_txn[4] {
1296                 assert_eq!(claim_txn[1], claim_txn[4]);
1297                 assert_eq!(claim_txn[2], claim_txn[5]);
1298
1299                 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1300
1301                 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1302                 &claim_txn[3]
1303         } else {
1304                 assert_eq!(claim_txn[1], claim_txn[3]);
1305                 assert_eq!(claim_txn[2], claim_txn[4]);
1306
1307                 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1308
1309                 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1310
1311                 &claim_txn[7]
1312         };
1313
1314         assert_eq!(claim_txn[0].input.len(), 1);
1315         assert_eq!(bump_tx.input.len(), 1);
1316         assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1317
1318         assert_eq!(claim_txn[0].input.len(), 1);
1319         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1320         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1321
1322         assert_eq!(claim_txn[6].input.len(), 1);
1323         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1324         check_spends!(claim_txn[6], remote_txn[0]);
1325         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1326
1327         let events = nodes[0].node.get_and_clear_pending_msg_events();
1328         assert_eq!(events.len(), 3);
1329         for e in events {
1330                 match e {
1331                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1332                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1333                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1334                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1335                         },
1336                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1337                                 assert!(update_add_htlcs.is_empty());
1338                                 assert!(update_fail_htlcs.is_empty());
1339                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1340                                 assert!(update_fail_malformed_htlcs.is_empty());
1341                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1342                         },
1343                         _ => panic!("Unexpected event"),
1344                 }
1345         }
1346 }
1347
1348 #[test]
1349 fn test_basic_channel_reserve() {
1350         let chanmon_cfgs = create_chanmon_cfgs(2);
1351         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1352         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1353         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1354         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1355
1356         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1357         let channel_reserve = chan_stat.channel_reserve_msat;
1358
1359         // The 2* and +1 are for the fee spike reserve.
1360         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1361         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1362         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1363         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1364         match err {
1365                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1366                         match &fails[0] {
1367                                 &APIError::ChannelUnavailable{ref err} =>
1368                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1369                                 _ => panic!("Unexpected error variant"),
1370                         }
1371                 },
1372                 _ => panic!("Unexpected error variant"),
1373         }
1374         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1375         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1376
1377         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1378 }
1379
1380 #[test]
1381 fn test_fee_spike_violation_fails_htlc() {
1382         let chanmon_cfgs = create_chanmon_cfgs(2);
1383         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1384         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1385         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1386         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1387
1388         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1389         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1390         let secp_ctx = Secp256k1::new();
1391         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1392
1393         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1394
1395         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1396         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1397         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1398         let msg = msgs::UpdateAddHTLC {
1399                 channel_id: chan.2,
1400                 htlc_id: 0,
1401                 amount_msat: htlc_msat,
1402                 payment_hash: payment_hash,
1403                 cltv_expiry: htlc_cltv,
1404                 onion_routing_packet: onion_packet,
1405         };
1406
1407         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1408
1409         // Now manually create the commitment_signed message corresponding to the update_add
1410         // nodes[0] just sent. In the code for construction of this message, "local" refers
1411         // to the sender of the message, and "remote" refers to the receiver.
1412
1413         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1414
1415         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1416
1417         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1418         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1419         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1420                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1421                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1422                 let chan_signer = local_chan.get_signer();
1423                 // Make the signer believe we validated another commitment, so we can release the secret
1424                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1425
1426                 let pubkeys = chan_signer.pubkeys();
1427                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1428                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1429                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1430                  chan_signer.pubkeys().funding_pubkey)
1431         };
1432         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1433                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1434                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1435                 let chan_signer = remote_chan.get_signer();
1436                 let pubkeys = chan_signer.pubkeys();
1437                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1438                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1439                  chan_signer.pubkeys().funding_pubkey)
1440         };
1441
1442         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1443         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1444                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1445
1446         // Build the remote commitment transaction so we can sign it, and then later use the
1447         // signature for the commitment_signed message.
1448         let local_chan_balance = 1313;
1449
1450         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1451                 offered: false,
1452                 amount_msat: 3460001,
1453                 cltv_expiry: htlc_cltv,
1454                 payment_hash,
1455                 transaction_output_index: Some(1),
1456         };
1457
1458         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1459
1460         let res = {
1461                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1462                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1463                 let local_chan_signer = local_chan.get_signer();
1464                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1465                         commitment_number,
1466                         95000,
1467                         local_chan_balance,
1468                         local_chan.opt_anchors(), local_funding, remote_funding,
1469                         commit_tx_keys.clone(),
1470                         feerate_per_kw,
1471                         &mut vec![(accepted_htlc_info, ())],
1472                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1473                 );
1474                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1475         };
1476
1477         let commit_signed_msg = msgs::CommitmentSigned {
1478                 channel_id: chan.2,
1479                 signature: res.0,
1480                 htlc_signatures: res.1
1481         };
1482
1483         // Send the commitment_signed message to the nodes[1].
1484         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1485         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1486
1487         // Send the RAA to nodes[1].
1488         let raa_msg = msgs::RevokeAndACK {
1489                 channel_id: chan.2,
1490                 per_commitment_secret: local_secret,
1491                 next_per_commitment_point: next_local_point
1492         };
1493         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1494
1495         let events = nodes[1].node.get_and_clear_pending_msg_events();
1496         assert_eq!(events.len(), 1);
1497         // Make sure the HTLC failed in the way we expect.
1498         match events[0] {
1499                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1500                         assert_eq!(update_fail_htlcs.len(), 1);
1501                         update_fail_htlcs[0].clone()
1502                 },
1503                 _ => panic!("Unexpected event"),
1504         };
1505         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1506                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1507
1508         check_added_monitors!(nodes[1], 2);
1509 }
1510
1511 #[test]
1512 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1513         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1514         // Set the fee rate for the channel very high, to the point where the fundee
1515         // sending any above-dust amount would result in a channel reserve violation.
1516         // In this test we check that we would be prevented from sending an HTLC in
1517         // this situation.
1518         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1519         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1520         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1521         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1522
1523         let opt_anchors = false;
1524
1525         let mut push_amt = 100_000_000;
1526         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1527         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1528
1529         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1530
1531         // Sending exactly enough to hit the reserve amount should be accepted
1532         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1533                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1534         }
1535
1536         // However one more HTLC should be significantly over the reserve amount and fail.
1537         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1538         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1539                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1540         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1541         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1542 }
1543
1544 #[test]
1545 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1546         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1547         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1548         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1549         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1550         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1551
1552         let opt_anchors = false;
1553
1554         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1555         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1556         // transaction fee with 0 HTLCs (183 sats)).
1557         let mut push_amt = 100_000_000;
1558         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1559         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1560         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1561
1562         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1563         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1564                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1565         }
1566
1567         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1568         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1569         let secp_ctx = Secp256k1::new();
1570         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1571         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1572         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1573         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1574         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1575         let msg = msgs::UpdateAddHTLC {
1576                 channel_id: chan.2,
1577                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1578                 amount_msat: htlc_msat,
1579                 payment_hash: payment_hash,
1580                 cltv_expiry: htlc_cltv,
1581                 onion_routing_packet: onion_packet,
1582         };
1583
1584         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1585         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1586         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1587         assert_eq!(nodes[0].node.list_channels().len(), 0);
1588         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1589         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1590         check_added_monitors!(nodes[0], 1);
1591         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() });
1592 }
1593
1594 #[test]
1595 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1596         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1597         // calculating our commitment transaction fee (this was previously broken).
1598         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1599         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1600
1601         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1602         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1603         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1604
1605         let opt_anchors = false;
1606
1607         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1608         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1609         // transaction fee with 0 HTLCs (183 sats)).
1610         let mut push_amt = 100_000_000;
1611         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1612         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1613         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1614
1615         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1616                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1617         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1618         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1619         // commitment transaction fee.
1620         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1621
1622         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1623         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1624                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1625         }
1626
1627         // One more than the dust amt should fail, however.
1628         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1629         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1630                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1631 }
1632
1633 #[test]
1634 fn test_chan_init_feerate_unaffordability() {
1635         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1636         // channel reserve and feerate requirements.
1637         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1638         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1639         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1640         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1641         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1642
1643         let opt_anchors = false;
1644
1645         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1646         // HTLC.
1647         let mut push_amt = 100_000_000;
1648         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1649         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1650                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1651
1652         // During open, we don't have a "counterparty channel reserve" to check against, so that
1653         // requirement only comes into play on the open_channel handling side.
1654         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1655         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1656         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1657         open_channel_msg.push_msat += 1;
1658         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1659
1660         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1661         assert_eq!(msg_events.len(), 1);
1662         match msg_events[0] {
1663                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1664                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1665                 },
1666                 _ => panic!("Unexpected event"),
1667         }
1668 }
1669
1670 #[test]
1671 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1672         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1673         // calculating our counterparty's commitment transaction fee (this was previously broken).
1674         let chanmon_cfgs = create_chanmon_cfgs(2);
1675         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1676         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1677         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1678         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1679
1680         let payment_amt = 46000; // Dust amount
1681         // In the previous code, these first four payments would succeed.
1682         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1683         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1684         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1686
1687         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1688         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1690         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1691         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1693
1694         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1695         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1696         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1697         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1698 }
1699
1700 #[test]
1701 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1702         let chanmon_cfgs = create_chanmon_cfgs(3);
1703         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1704         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1705         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1706         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1707         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1708
1709         let feemsat = 239;
1710         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1711         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1712         let feerate = get_feerate!(nodes[0], chan.2);
1713         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1714
1715         // Add a 2* and +1 for the fee spike reserve.
1716         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1717         let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1718         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1719
1720         // Add a pending HTLC.
1721         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1722         let payment_event_1 = {
1723                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1724                 check_added_monitors!(nodes[0], 1);
1725
1726                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1727                 assert_eq!(events.len(), 1);
1728                 SendEvent::from_event(events.remove(0))
1729         };
1730         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1731
1732         // Attempt to trigger a channel reserve violation --> payment failure.
1733         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1734         let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1735         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1736         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1737
1738         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1739         let secp_ctx = Secp256k1::new();
1740         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1741         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1742         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1743         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1744         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1745         let msg = msgs::UpdateAddHTLC {
1746                 channel_id: chan.2,
1747                 htlc_id: 1,
1748                 amount_msat: htlc_msat + 1,
1749                 payment_hash: our_payment_hash_1,
1750                 cltv_expiry: htlc_cltv,
1751                 onion_routing_packet: onion_packet,
1752         };
1753
1754         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1755         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1756         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1757         assert_eq!(nodes[1].node.list_channels().len(), 1);
1758         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1759         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1760         check_added_monitors!(nodes[1], 1);
1761         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1762 }
1763
1764 #[test]
1765 fn test_inbound_outbound_capacity_is_not_zero() {
1766         let chanmon_cfgs = create_chanmon_cfgs(2);
1767         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1768         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1769         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1770         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1771         let channels0 = node_chanmgrs[0].list_channels();
1772         let channels1 = node_chanmgrs[1].list_channels();
1773         assert_eq!(channels0.len(), 1);
1774         assert_eq!(channels1.len(), 1);
1775
1776         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1777         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1778         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1779
1780         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1781         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1782 }
1783
1784 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1785         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1786 }
1787
1788 #[test]
1789 fn test_channel_reserve_holding_cell_htlcs() {
1790         let chanmon_cfgs = create_chanmon_cfgs(3);
1791         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1792         // When this test was written, the default base fee floated based on the HTLC count.
1793         // It is now fixed, so we simply set the fee to the expected value here.
1794         let mut config = test_default_channel_config();
1795         config.channel_config.forwarding_fee_base_msat = 239;
1796         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1797         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1798         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1799         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1800
1801         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1802         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1803
1804         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1805         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1806
1807         macro_rules! expect_forward {
1808                 ($node: expr) => {{
1809                         let mut events = $node.node.get_and_clear_pending_msg_events();
1810                         assert_eq!(events.len(), 1);
1811                         check_added_monitors!($node, 1);
1812                         let payment_event = SendEvent::from_event(events.remove(0));
1813                         payment_event
1814                 }}
1815         }
1816
1817         let feemsat = 239; // set above
1818         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1819         let feerate = get_feerate!(nodes[0], chan_1.2);
1820         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1821
1822         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1823
1824         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1825         {
1826                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1827                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1828                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1829                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1830                         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)));
1831                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1832                 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);
1833         }
1834
1835         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1836         // nodes[0]'s wealth
1837         loop {
1838                 let amt_msat = recv_value_0 + total_fee_msat;
1839                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1840                 // Also, ensure that each payment has enough to be over the dust limit to
1841                 // ensure it'll be included in each commit tx fee calculation.
1842                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1843                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1844                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1845                         break;
1846                 }
1847                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1848
1849                 let (stat01_, stat11_, stat12_, stat22_) = (
1850                         get_channel_value_stat!(nodes[0], chan_1.2),
1851                         get_channel_value_stat!(nodes[1], chan_1.2),
1852                         get_channel_value_stat!(nodes[1], chan_2.2),
1853                         get_channel_value_stat!(nodes[2], chan_2.2),
1854                 );
1855
1856                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1857                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1858                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1859                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1860                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1861         }
1862
1863         // adding pending output.
1864         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1865         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1866         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1867         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1868         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1869         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1870         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1871         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1872         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1873         // policy.
1874         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1875         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1876         let amt_msat_1 = recv_value_1 + total_fee_msat;
1877
1878         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);
1879         let payment_event_1 = {
1880                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1881                 check_added_monitors!(nodes[0], 1);
1882
1883                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1884                 assert_eq!(events.len(), 1);
1885                 SendEvent::from_event(events.remove(0))
1886         };
1887         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1888
1889         // channel reserve test with htlc pending output > 0
1890         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1891         {
1892                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1893                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1894                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1895                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1896         }
1897
1898         // split the rest to test holding cell
1899         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1900         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1901         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1902         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1903         {
1904                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1905                 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);
1906         }
1907
1908         // now see if they go through on both sides
1909         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);
1910         // but this will stuck in the holding cell
1911         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1912         check_added_monitors!(nodes[0], 0);
1913         let events = nodes[0].node.get_and_clear_pending_events();
1914         assert_eq!(events.len(), 0);
1915
1916         // test with outbound holding cell amount > 0
1917         {
1918                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1919                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1920                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1921                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1922                 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);
1923         }
1924
1925         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);
1926         // this will also stuck in the holding cell
1927         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1928         check_added_monitors!(nodes[0], 0);
1929         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1930         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1931
1932         // flush the pending htlc
1933         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1934         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1935         check_added_monitors!(nodes[1], 1);
1936
1937         // the pending htlc should be promoted to committed
1938         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1939         check_added_monitors!(nodes[0], 1);
1940         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1941
1942         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1943         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1944         // No commitment_signed so get_event_msg's assert(len == 1) passes
1945         check_added_monitors!(nodes[0], 1);
1946
1947         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1948         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1949         check_added_monitors!(nodes[1], 1);
1950
1951         expect_pending_htlcs_forwardable!(nodes[1]);
1952
1953         let ref payment_event_11 = expect_forward!(nodes[1]);
1954         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1955         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1956
1957         expect_pending_htlcs_forwardable!(nodes[2]);
1958         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1959
1960         // flush the htlcs in the holding cell
1961         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1962         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1963         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1964         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1965         expect_pending_htlcs_forwardable!(nodes[1]);
1966
1967         let ref payment_event_3 = expect_forward!(nodes[1]);
1968         assert_eq!(payment_event_3.msgs.len(), 2);
1969         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1970         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1971
1972         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1973         expect_pending_htlcs_forwardable!(nodes[2]);
1974
1975         let events = nodes[2].node.get_and_clear_pending_events();
1976         assert_eq!(events.len(), 2);
1977         match events[0] {
1978                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1979                         assert_eq!(our_payment_hash_21, *payment_hash);
1980                         assert_eq!(recv_value_21, amount_msat);
1981                         match &purpose {
1982                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1983                                         assert!(payment_preimage.is_none());
1984                                         assert_eq!(our_payment_secret_21, *payment_secret);
1985                                 },
1986                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1987                         }
1988                 },
1989                 _ => panic!("Unexpected event"),
1990         }
1991         match events[1] {
1992                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1993                         assert_eq!(our_payment_hash_22, *payment_hash);
1994                         assert_eq!(recv_value_22, amount_msat);
1995                         match &purpose {
1996                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1997                                         assert!(payment_preimage.is_none());
1998                                         assert_eq!(our_payment_secret_22, *payment_secret);
1999                                 },
2000                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2001                         }
2002                 },
2003                 _ => panic!("Unexpected event"),
2004         }
2005
2006         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2007         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2008         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2009
2010         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2011         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2012         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2013
2014         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2015         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);
2016         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2017         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2018         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2019
2020         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2021         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2022 }
2023
2024 #[test]
2025 fn channel_reserve_in_flight_removes() {
2026         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2027         // can send to its counterparty, but due to update ordering, the other side may not yet have
2028         // considered those HTLCs fully removed.
2029         // This tests that we don't count HTLCs which will not be included in the next remote
2030         // commitment transaction towards the reserve value (as it implies no commitment transaction
2031         // will be generated which violates the remote reserve value).
2032         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2033         // To test this we:
2034         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2035         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2036         //    you only consider the value of the first HTLC, it may not),
2037         //  * start routing a third HTLC from A to B,
2038         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2039         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2040         //  * deliver the first fulfill from B
2041         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2042         //    claim,
2043         //  * deliver A's response CS and RAA.
2044         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2045         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2046         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2047         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2048         let chanmon_cfgs = create_chanmon_cfgs(2);
2049         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2050         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2051         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2052         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2053
2054         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2055         // Route the first two HTLCs.
2056         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2057         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2058         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2059
2060         // Start routing the third HTLC (this is just used to get everyone in the right state).
2061         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2062         let send_1 = {
2063                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2064                 check_added_monitors!(nodes[0], 1);
2065                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2066                 assert_eq!(events.len(), 1);
2067                 SendEvent::from_event(events.remove(0))
2068         };
2069
2070         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2071         // initial fulfill/CS.
2072         nodes[1].node.claim_funds(payment_preimage_1);
2073         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2074         check_added_monitors!(nodes[1], 1);
2075         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2076
2077         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2078         // remove the second HTLC when we send the HTLC back from B to A.
2079         nodes[1].node.claim_funds(payment_preimage_2);
2080         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2081         check_added_monitors!(nodes[1], 1);
2082         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2083
2084         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2085         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2086         check_added_monitors!(nodes[0], 1);
2087         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2088         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2089
2090         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2091         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2092         check_added_monitors!(nodes[1], 1);
2093         // B is already AwaitingRAA, so cant generate a CS here
2094         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2095
2096         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2097         check_added_monitors!(nodes[1], 1);
2098         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2099
2100         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2101         check_added_monitors!(nodes[0], 1);
2102         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2103
2104         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2105         check_added_monitors!(nodes[1], 1);
2106         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2107
2108         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2109         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2110         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2111         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2112         // on-chain as necessary).
2113         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2114         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2115         check_added_monitors!(nodes[0], 1);
2116         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2117         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2118
2119         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2120         check_added_monitors!(nodes[1], 1);
2121         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2122
2123         expect_pending_htlcs_forwardable!(nodes[1]);
2124         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2125
2126         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2127         // resolve the second HTLC from A's point of view.
2128         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2129         check_added_monitors!(nodes[0], 1);
2130         expect_payment_path_successful!(nodes[0]);
2131         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2132
2133         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2134         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2135         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2136         let send_2 = {
2137                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2138                 check_added_monitors!(nodes[1], 1);
2139                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2140                 assert_eq!(events.len(), 1);
2141                 SendEvent::from_event(events.remove(0))
2142         };
2143
2144         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2145         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2146         check_added_monitors!(nodes[0], 1);
2147         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2148
2149         // Now just resolve all the outstanding messages/HTLCs for completeness...
2150
2151         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2152         check_added_monitors!(nodes[1], 1);
2153         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2154
2155         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2156         check_added_monitors!(nodes[1], 1);
2157
2158         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2159         check_added_monitors!(nodes[0], 1);
2160         expect_payment_path_successful!(nodes[0]);
2161         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2162
2163         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2164         check_added_monitors!(nodes[1], 1);
2165         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
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
2170         expect_pending_htlcs_forwardable!(nodes[0]);
2171         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2172
2173         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2174         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2175 }
2176
2177 #[test]
2178 fn channel_monitor_network_test() {
2179         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2180         // tests that ChannelMonitor is able to recover from various states.
2181         let chanmon_cfgs = create_chanmon_cfgs(5);
2182         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2183         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2184         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2185
2186         // Create some initial channels
2187         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2188         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2189         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2190         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2191
2192         // Make sure all nodes are at the same starting height
2193         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2194         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2195         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2196         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2197         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2198
2199         // Rebalance the network a bit by relaying one payment through all the channels...
2200         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2201         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2202         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2203         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2204
2205         // Simple case with no pending HTLCs:
2206         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2207         check_added_monitors!(nodes[1], 1);
2208         check_closed_broadcast!(nodes[1], true);
2209         {
2210                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2211                 assert_eq!(node_txn.len(), 1);
2212                 mine_transaction(&nodes[0], &node_txn[0]);
2213                 check_added_monitors!(nodes[0], 1);
2214                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2215         }
2216         check_closed_broadcast!(nodes[0], true);
2217         assert_eq!(nodes[0].node.list_channels().len(), 0);
2218         assert_eq!(nodes[1].node.list_channels().len(), 1);
2219         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2220         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2221
2222         // One pending HTLC is discarded by the force-close:
2223         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2224
2225         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2226         // broadcasted until we reach the timelock time).
2227         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2228         check_closed_broadcast!(nodes[1], true);
2229         check_added_monitors!(nodes[1], 1);
2230         {
2231                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2232                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2233                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2234                 mine_transaction(&nodes[2], &node_txn[0]);
2235                 check_added_monitors!(nodes[2], 1);
2236                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2237         }
2238         check_closed_broadcast!(nodes[2], true);
2239         assert_eq!(nodes[1].node.list_channels().len(), 0);
2240         assert_eq!(nodes[2].node.list_channels().len(), 1);
2241         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2242         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2243
2244         macro_rules! claim_funds {
2245                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2246                         {
2247                                 $node.node.claim_funds($preimage);
2248                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2249                                 check_added_monitors!($node, 1);
2250
2251                                 let events = $node.node.get_and_clear_pending_msg_events();
2252                                 assert_eq!(events.len(), 1);
2253                                 match events[0] {
2254                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2255                                                 assert!(update_add_htlcs.is_empty());
2256                                                 assert!(update_fail_htlcs.is_empty());
2257                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2258                                         },
2259                                         _ => panic!("Unexpected event"),
2260                                 };
2261                         }
2262                 }
2263         }
2264
2265         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2266         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2267         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2268         check_added_monitors!(nodes[2], 1);
2269         check_closed_broadcast!(nodes[2], true);
2270         let node2_commitment_txid;
2271         {
2272                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2273                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2274                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2275                 node2_commitment_txid = node_txn[0].txid();
2276
2277                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2278                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2279                 mine_transaction(&nodes[3], &node_txn[0]);
2280                 check_added_monitors!(nodes[3], 1);
2281                 check_preimage_claim(&nodes[3], &node_txn);
2282         }
2283         check_closed_broadcast!(nodes[3], true);
2284         assert_eq!(nodes[2].node.list_channels().len(), 0);
2285         assert_eq!(nodes[3].node.list_channels().len(), 1);
2286         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2287         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2288
2289         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2290         // confusing us in the following tests.
2291         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2292
2293         // One pending HTLC to time out:
2294         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2295         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2296         // buffer space).
2297
2298         let (close_chan_update_1, close_chan_update_2) = {
2299                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2300                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2301                 assert_eq!(events.len(), 2);
2302                 let close_chan_update_1 = match events[0] {
2303                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2304                                 msg.clone()
2305                         },
2306                         _ => panic!("Unexpected event"),
2307                 };
2308                 match events[1] {
2309                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2310                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2311                         },
2312                         _ => panic!("Unexpected event"),
2313                 }
2314                 check_added_monitors!(nodes[3], 1);
2315
2316                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2317                 {
2318                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2319                         node_txn.retain(|tx| {
2320                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2321                                         false
2322                                 } else { true }
2323                         });
2324                 }
2325
2326                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2327
2328                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2329                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2330
2331                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2332                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2333                 assert_eq!(events.len(), 2);
2334                 let close_chan_update_2 = match events[0] {
2335                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2336                                 msg.clone()
2337                         },
2338                         _ => panic!("Unexpected event"),
2339                 };
2340                 match events[1] {
2341                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2342                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2343                         },
2344                         _ => panic!("Unexpected event"),
2345                 }
2346                 check_added_monitors!(nodes[4], 1);
2347                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2348
2349                 mine_transaction(&nodes[4], &node_txn[0]);
2350                 check_preimage_claim(&nodes[4], &node_txn);
2351                 (close_chan_update_1, close_chan_update_2)
2352         };
2353         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2354         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2355         assert_eq!(nodes[3].node.list_channels().len(), 0);
2356         assert_eq!(nodes[4].node.list_channels().len(), 0);
2357
2358         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2359         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2360         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2361 }
2362
2363 #[test]
2364 fn test_justice_tx() {
2365         // Test justice txn built on revoked HTLC-Success tx, against both sides
2366         let mut alice_config = UserConfig::default();
2367         alice_config.channel_handshake_config.announced_channel = true;
2368         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2369         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2370         let mut bob_config = UserConfig::default();
2371         bob_config.channel_handshake_config.announced_channel = true;
2372         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2373         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2374         let user_cfgs = [Some(alice_config), Some(bob_config)];
2375         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2376         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2377         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2378         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2379         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2380         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2381         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2382         // Create some new channels:
2383         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2384
2385         // A pending HTLC which will be revoked:
2386         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2387         // Get the will-be-revoked local txn from nodes[0]
2388         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2389         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2390         assert_eq!(revoked_local_txn[0].input.len(), 1);
2391         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2392         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2393         assert_eq!(revoked_local_txn[1].input.len(), 1);
2394         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2395         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2396         // Revoke the old state
2397         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2398
2399         {
2400                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2401                 {
2402                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2403                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2404                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2405
2406                         check_spends!(node_txn[0], revoked_local_txn[0]);
2407                         node_txn.swap_remove(0);
2408                         node_txn.truncate(1);
2409                 }
2410                 check_added_monitors!(nodes[1], 1);
2411                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2412                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2413
2414                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2415                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2416                 // Verify broadcast of revoked HTLC-timeout
2417                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2418                 check_added_monitors!(nodes[0], 1);
2419                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2420                 // Broadcast revoked HTLC-timeout on node 1
2421                 mine_transaction(&nodes[1], &node_txn[1]);
2422                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2423         }
2424         get_announce_close_broadcast_events(&nodes, 0, 1);
2425
2426         assert_eq!(nodes[0].node.list_channels().len(), 0);
2427         assert_eq!(nodes[1].node.list_channels().len(), 0);
2428
2429         // We test justice_tx build by A on B's revoked HTLC-Success tx
2430         // Create some new channels:
2431         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2432         {
2433                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2434                 node_txn.clear();
2435         }
2436
2437         // A pending HTLC which will be revoked:
2438         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2439         // Get the will-be-revoked local txn from B
2440         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2441         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2442         assert_eq!(revoked_local_txn[0].input.len(), 1);
2443         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2444         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2445         // Revoke the old state
2446         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2447         {
2448                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2449                 {
2450                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2451                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2452                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2453
2454                         check_spends!(node_txn[0], revoked_local_txn[0]);
2455                         node_txn.swap_remove(0);
2456                 }
2457                 check_added_monitors!(nodes[0], 1);
2458                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2459
2460                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2461                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2462                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2463                 check_added_monitors!(nodes[1], 1);
2464                 mine_transaction(&nodes[0], &node_txn[1]);
2465                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2466                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2467         }
2468         get_announce_close_broadcast_events(&nodes, 0, 1);
2469         assert_eq!(nodes[0].node.list_channels().len(), 0);
2470         assert_eq!(nodes[1].node.list_channels().len(), 0);
2471 }
2472
2473 #[test]
2474 fn revoked_output_claim() {
2475         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2476         // transaction is broadcast by its counterparty
2477         let chanmon_cfgs = create_chanmon_cfgs(2);
2478         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2479         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2480         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2481         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2482         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2483         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2484         assert_eq!(revoked_local_txn.len(), 1);
2485         // Only output is the full channel value back to nodes[0]:
2486         assert_eq!(revoked_local_txn[0].output.len(), 1);
2487         // Send a payment through, updating everyone's latest commitment txn
2488         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2489
2490         // Inform nodes[1] that nodes[0] broadcast a stale tx
2491         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2492         check_added_monitors!(nodes[1], 1);
2493         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2494         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2495         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2496
2497         check_spends!(node_txn[0], revoked_local_txn[0]);
2498         check_spends!(node_txn[1], chan_1.3);
2499
2500         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2501         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2502         get_announce_close_broadcast_events(&nodes, 0, 1);
2503         check_added_monitors!(nodes[0], 1);
2504         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2505 }
2506
2507 #[test]
2508 fn claim_htlc_outputs_shared_tx() {
2509         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2510         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2511         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2512         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2513         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2514         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2515
2516         // Create some new channel:
2517         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2518
2519         // Rebalance the network to generate htlc in the two directions
2520         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2521         // 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
2522         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2523         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2524
2525         // Get the will-be-revoked local txn from node[0]
2526         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2527         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2528         assert_eq!(revoked_local_txn[0].input.len(), 1);
2529         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2530         assert_eq!(revoked_local_txn[1].input.len(), 1);
2531         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2532         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2533         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2534
2535         //Revoke the old state
2536         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2537
2538         {
2539                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2540                 check_added_monitors!(nodes[0], 1);
2541                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2542                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2543                 check_added_monitors!(nodes[1], 1);
2544                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2545                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2546                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2547
2548                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2549                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2550
2551                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2552                 check_spends!(node_txn[0], revoked_local_txn[0]);
2553
2554                 let mut witness_lens = BTreeSet::new();
2555                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2556                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2557                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2558                 assert_eq!(witness_lens.len(), 3);
2559                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2560                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2561                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2562
2563                 // Next nodes[1] broadcasts its current local tx state:
2564                 assert_eq!(node_txn[1].input.len(), 1);
2565                 check_spends!(node_txn[1], chan_1.3);
2566
2567                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2568                 // ANTI_REORG_DELAY confirmations.
2569                 mine_transaction(&nodes[1], &node_txn[0]);
2570                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2571                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2572         }
2573         get_announce_close_broadcast_events(&nodes, 0, 1);
2574         assert_eq!(nodes[0].node.list_channels().len(), 0);
2575         assert_eq!(nodes[1].node.list_channels().len(), 0);
2576 }
2577
2578 #[test]
2579 fn claim_htlc_outputs_single_tx() {
2580         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2581         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2582         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2583         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2584         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2585         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2586
2587         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2588
2589         // Rebalance the network to generate htlc in the two directions
2590         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2591         // 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
2592         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2593         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2594         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2595
2596         // Get the will-be-revoked local txn from node[0]
2597         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2598
2599         //Revoke the old state
2600         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2601
2602         {
2603                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2604                 check_added_monitors!(nodes[0], 1);
2605                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2606                 check_added_monitors!(nodes[1], 1);
2607                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2608                 let mut events = nodes[0].node.get_and_clear_pending_events();
2609                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2610                 match events[1] {
2611                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2612                         _ => panic!("Unexpected event"),
2613                 }
2614
2615                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2616                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2617
2618                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2619                 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2620
2621                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2622                 assert_eq!(node_txn[0].input.len(), 1);
2623                 check_spends!(node_txn[0], chan_1.3);
2624                 assert_eq!(node_txn[1].input.len(), 1);
2625                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2626                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2627                 check_spends!(node_txn[1], node_txn[0]);
2628
2629                 // Justice transactions are indices 1-2-4
2630                 assert_eq!(node_txn[2].input.len(), 1);
2631                 assert_eq!(node_txn[3].input.len(), 1);
2632                 assert_eq!(node_txn[4].input.len(), 1);
2633
2634                 check_spends!(node_txn[2], revoked_local_txn[0]);
2635                 check_spends!(node_txn[3], revoked_local_txn[0]);
2636                 check_spends!(node_txn[4], revoked_local_txn[0]);
2637
2638                 let mut witness_lens = BTreeSet::new();
2639                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2640                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2641                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2642                 assert_eq!(witness_lens.len(), 3);
2643                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2644                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2645                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2646
2647                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2648                 // ANTI_REORG_DELAY confirmations.
2649                 mine_transaction(&nodes[1], &node_txn[2]);
2650                 mine_transaction(&nodes[1], &node_txn[3]);
2651                 mine_transaction(&nodes[1], &node_txn[4]);
2652                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2653                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2654         }
2655         get_announce_close_broadcast_events(&nodes, 0, 1);
2656         assert_eq!(nodes[0].node.list_channels().len(), 0);
2657         assert_eq!(nodes[1].node.list_channels().len(), 0);
2658 }
2659
2660 #[test]
2661 fn test_htlc_on_chain_success() {
2662         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2663         // the preimage backward accordingly. So here we test that ChannelManager is
2664         // broadcasting the right event to other nodes in payment path.
2665         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2666         // A --------------------> B ----------------------> C (preimage)
2667         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2668         // commitment transaction was broadcast.
2669         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2670         // towards B.
2671         // B should be able to claim via preimage if A then broadcasts its local tx.
2672         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2673         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2674         // PaymentSent event).
2675
2676         let chanmon_cfgs = create_chanmon_cfgs(3);
2677         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2678         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2679         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2680
2681         // Create some initial channels
2682         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2683         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2684
2685         // Ensure all nodes are at the same height
2686         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2687         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2688         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2689         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2690
2691         // Rebalance the network a bit by relaying one payment through all the channels...
2692         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2693         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2694
2695         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2696         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2697
2698         // Broadcast legit commitment tx from C on B's chain
2699         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2700         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2701         assert_eq!(commitment_tx.len(), 1);
2702         check_spends!(commitment_tx[0], chan_2.3);
2703         nodes[2].node.claim_funds(our_payment_preimage);
2704         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2705         nodes[2].node.claim_funds(our_payment_preimage_2);
2706         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2707         check_added_monitors!(nodes[2], 2);
2708         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2709         assert!(updates.update_add_htlcs.is_empty());
2710         assert!(updates.update_fail_htlcs.is_empty());
2711         assert!(updates.update_fail_malformed_htlcs.is_empty());
2712         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2713
2714         mine_transaction(&nodes[2], &commitment_tx[0]);
2715         check_closed_broadcast!(nodes[2], true);
2716         check_added_monitors!(nodes[2], 1);
2717         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2718         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)
2719         assert_eq!(node_txn.len(), 5);
2720         assert_eq!(node_txn[0], node_txn[3]);
2721         assert_eq!(node_txn[1], node_txn[4]);
2722         assert_eq!(node_txn[2], commitment_tx[0]);
2723         check_spends!(node_txn[0], commitment_tx[0]);
2724         check_spends!(node_txn[1], commitment_tx[0]);
2725         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2726         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2727         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2728         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2729         assert_eq!(node_txn[0].lock_time, 0);
2730         assert_eq!(node_txn[1].lock_time, 0);
2731
2732         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2733         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2734         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2735         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2736         {
2737                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2738                 assert_eq!(added_monitors.len(), 1);
2739                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2740                 added_monitors.clear();
2741         }
2742         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2743         assert_eq!(forwarded_events.len(), 3);
2744         match forwarded_events[0] {
2745                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2746                 _ => panic!("Unexpected event"),
2747         }
2748         let chan_id = Some(chan_1.2);
2749         match forwarded_events[1] {
2750                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2751                         assert_eq!(fee_earned_msat, Some(1000));
2752                         assert_eq!(prev_channel_id, chan_id);
2753                         assert_eq!(claim_from_onchain_tx, true);
2754                         assert_eq!(next_channel_id, Some(chan_2.2));
2755                 },
2756                 _ => panic!()
2757         }
2758         match forwarded_events[2] {
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         let events = nodes[1].node.get_and_clear_pending_msg_events();
2768         {
2769                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2770                 assert_eq!(added_monitors.len(), 2);
2771                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2772                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2773                 added_monitors.clear();
2774         }
2775         assert_eq!(events.len(), 3);
2776         match events[0] {
2777                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2778                 _ => panic!("Unexpected event"),
2779         }
2780         match events[1] {
2781                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2782                 _ => panic!("Unexpected event"),
2783         }
2784
2785         match events[2] {
2786                 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, .. } } => {
2787                         assert!(update_add_htlcs.is_empty());
2788                         assert!(update_fail_htlcs.is_empty());
2789                         assert_eq!(update_fulfill_htlcs.len(), 1);
2790                         assert!(update_fail_malformed_htlcs.is_empty());
2791                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2792                 },
2793                 _ => panic!("Unexpected event"),
2794         };
2795         macro_rules! check_tx_local_broadcast {
2796                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2797                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2798                         assert_eq!(node_txn.len(), 3);
2799                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2800                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2801                         check_spends!(node_txn[1], $commitment_tx);
2802                         check_spends!(node_txn[2], $commitment_tx);
2803                         assert_ne!(node_txn[1].lock_time, 0);
2804                         assert_ne!(node_txn[2].lock_time, 0);
2805                         if $htlc_offered {
2806                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2807                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2808                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2809                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2810                         } else {
2811                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2812                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2813                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2814                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2815                         }
2816                         check_spends!(node_txn[0], $chan_tx);
2817                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2818                         node_txn.clear();
2819                 } }
2820         }
2821         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2822         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2823         // timeout-claim of the output that nodes[2] just claimed via success.
2824         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2825
2826         // Broadcast legit commitment tx from A on B's chain
2827         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2828         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2829         check_spends!(node_a_commitment_tx[0], chan_1.3);
2830         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2831         check_closed_broadcast!(nodes[1], true);
2832         check_added_monitors!(nodes[1], 1);
2833         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2834         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2835         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2836         let commitment_spend =
2837                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2838                         check_spends!(node_txn[1], commitment_tx[0]);
2839                         check_spends!(node_txn[2], commitment_tx[0]);
2840                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2841                         &node_txn[0]
2842                 } else {
2843                         check_spends!(node_txn[0], commitment_tx[0]);
2844                         check_spends!(node_txn[1], commitment_tx[0]);
2845                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2846                         &node_txn[2]
2847                 };
2848
2849         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2850         assert_eq!(commitment_spend.input.len(), 2);
2851         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2852         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2853         assert_eq!(commitment_spend.lock_time, 0);
2854         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2855         check_spends!(node_txn[3], chan_1.3);
2856         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2857         check_spends!(node_txn[4], node_txn[3]);
2858         check_spends!(node_txn[5], node_txn[3]);
2859         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2860         // we already checked the same situation with A.
2861
2862         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2863         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2864         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2865         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2866         check_closed_broadcast!(nodes[0], true);
2867         check_added_monitors!(nodes[0], 1);
2868         let events = nodes[0].node.get_and_clear_pending_events();
2869         assert_eq!(events.len(), 5);
2870         let mut first_claimed = false;
2871         for event in events {
2872                 match event {
2873                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2874                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2875                                         assert!(!first_claimed);
2876                                         first_claimed = true;
2877                                 } else {
2878                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2879                                         assert_eq!(payment_hash, payment_hash_2);
2880                                 }
2881                         },
2882                         Event::PaymentPathSuccessful { .. } => {},
2883                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2884                         _ => panic!("Unexpected event"),
2885                 }
2886         }
2887         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2888 }
2889
2890 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2891         // Test that in case of a unilateral close onchain, we detect the state of output and
2892         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2893         // broadcasting the right event to other nodes in payment path.
2894         // A ------------------> B ----------------------> C (timeout)
2895         //    B's commitment tx                 C's commitment tx
2896         //            \                                  \
2897         //         B's HTLC timeout tx               B's timeout tx
2898
2899         let chanmon_cfgs = create_chanmon_cfgs(3);
2900         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2901         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2902         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2903         *nodes[0].connect_style.borrow_mut() = connect_style;
2904         *nodes[1].connect_style.borrow_mut() = connect_style;
2905         *nodes[2].connect_style.borrow_mut() = connect_style;
2906
2907         // Create some intial channels
2908         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2909         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2910
2911         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2912         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2913         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2914
2915         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2916
2917         // Broadcast legit commitment tx from C on B's chain
2918         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2919         check_spends!(commitment_tx[0], chan_2.3);
2920         nodes[2].node.fail_htlc_backwards(&payment_hash);
2921         check_added_monitors!(nodes[2], 0);
2922         expect_pending_htlcs_forwardable!(nodes[2]);
2923         check_added_monitors!(nodes[2], 1);
2924
2925         let events = nodes[2].node.get_and_clear_pending_msg_events();
2926         assert_eq!(events.len(), 1);
2927         match events[0] {
2928                 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, .. } } => {
2929                         assert!(update_add_htlcs.is_empty());
2930                         assert!(!update_fail_htlcs.is_empty());
2931                         assert!(update_fulfill_htlcs.is_empty());
2932                         assert!(update_fail_malformed_htlcs.is_empty());
2933                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2934                 },
2935                 _ => panic!("Unexpected event"),
2936         };
2937         mine_transaction(&nodes[2], &commitment_tx[0]);
2938         check_closed_broadcast!(nodes[2], true);
2939         check_added_monitors!(nodes[2], 1);
2940         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2941         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2942         assert_eq!(node_txn.len(), 1);
2943         check_spends!(node_txn[0], chan_2.3);
2944         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2945
2946         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2947         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2948         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2949         mine_transaction(&nodes[1], &commitment_tx[0]);
2950         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2951         let timeout_tx;
2952         {
2953                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2954                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2955                 assert_eq!(node_txn[0], node_txn[3]);
2956                 assert_eq!(node_txn[1], node_txn[4]);
2957
2958                 check_spends!(node_txn[2], commitment_tx[0]);
2959                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2960
2961                 check_spends!(node_txn[0], chan_2.3);
2962                 check_spends!(node_txn[1], node_txn[0]);
2963                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2964                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2965
2966                 timeout_tx = node_txn[2].clone();
2967                 node_txn.clear();
2968         }
2969
2970         mine_transaction(&nodes[1], &timeout_tx);
2971         check_added_monitors!(nodes[1], 1);
2972         check_closed_broadcast!(nodes[1], true);
2973         {
2974                 // B will rebroadcast a fee-bumped timeout transaction here.
2975                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2976                 assert_eq!(node_txn.len(), 1);
2977                 check_spends!(node_txn[0], commitment_tx[0]);
2978         }
2979
2980         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2981         {
2982                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2983                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2984                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2985                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2986                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2987                 if node_txn.len() == 1 {
2988                         check_spends!(node_txn[0], chan_2.3);
2989                 } else {
2990                         assert_eq!(node_txn.len(), 0);
2991                 }
2992         }
2993
2994         expect_pending_htlcs_forwardable!(nodes[1]);
2995         check_added_monitors!(nodes[1], 1);
2996         let events = nodes[1].node.get_and_clear_pending_msg_events();
2997         assert_eq!(events.len(), 1);
2998         match events[0] {
2999                 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, .. } } => {
3000                         assert!(update_add_htlcs.is_empty());
3001                         assert!(!update_fail_htlcs.is_empty());
3002                         assert!(update_fulfill_htlcs.is_empty());
3003                         assert!(update_fail_malformed_htlcs.is_empty());
3004                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3005                 },
3006                 _ => panic!("Unexpected event"),
3007         };
3008
3009         // Broadcast legit commitment tx from B on A's chain
3010         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3011         check_spends!(commitment_tx[0], chan_1.3);
3012
3013         mine_transaction(&nodes[0], &commitment_tx[0]);
3014         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3015
3016         check_closed_broadcast!(nodes[0], true);
3017         check_added_monitors!(nodes[0], 1);
3018         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3019         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3020         assert_eq!(node_txn.len(), 2);
3021         check_spends!(node_txn[0], chan_1.3);
3022         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3023         check_spends!(node_txn[1], commitment_tx[0]);
3024         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3025 }
3026
3027 #[test]
3028 fn test_htlc_on_chain_timeout() {
3029         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3030         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3031         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3032 }
3033
3034 #[test]
3035 fn test_simple_commitment_revoked_fail_backward() {
3036         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3037         // and fail backward accordingly.
3038
3039         let chanmon_cfgs = create_chanmon_cfgs(3);
3040         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3041         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3042         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3043
3044         // Create some initial channels
3045         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3046         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3047
3048         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3049         // Get the will-be-revoked local txn from nodes[2]
3050         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3051         // Revoke the old state
3052         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3053
3054         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3055
3056         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3057         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3058         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3059         check_added_monitors!(nodes[1], 1);
3060         check_closed_broadcast!(nodes[1], true);
3061
3062         expect_pending_htlcs_forwardable!(nodes[1]);
3063         check_added_monitors!(nodes[1], 1);
3064         let events = nodes[1].node.get_and_clear_pending_msg_events();
3065         assert_eq!(events.len(), 1);
3066         match events[0] {
3067                 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, .. } } => {
3068                         assert!(update_add_htlcs.is_empty());
3069                         assert_eq!(update_fail_htlcs.len(), 1);
3070                         assert!(update_fulfill_htlcs.is_empty());
3071                         assert!(update_fail_malformed_htlcs.is_empty());
3072                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3073
3074                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3075                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3076                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3077                 },
3078                 _ => panic!("Unexpected event"),
3079         }
3080 }
3081
3082 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3083         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3084         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3085         // commitment transaction anymore.
3086         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3087         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3088         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3089         // technically disallowed and we should probably handle it reasonably.
3090         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3091         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3092         // transactions:
3093         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3094         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3095         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3096         //   and once they revoke the previous commitment transaction (allowing us to send a new
3097         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3098         let chanmon_cfgs = create_chanmon_cfgs(3);
3099         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3100         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3101         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3102
3103         // Create some initial channels
3104         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3105         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3106
3107         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 });
3108         // Get the will-be-revoked local txn from nodes[2]
3109         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3110         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3111         // Revoke the old state
3112         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3113
3114         let value = if use_dust {
3115                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3116                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3117                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3118         } else { 3000000 };
3119
3120         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3121         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3122         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3123
3124         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3125         expect_pending_htlcs_forwardable!(nodes[2]);
3126         check_added_monitors!(nodes[2], 1);
3127         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3128         assert!(updates.update_add_htlcs.is_empty());
3129         assert!(updates.update_fulfill_htlcs.is_empty());
3130         assert!(updates.update_fail_malformed_htlcs.is_empty());
3131         assert_eq!(updates.update_fail_htlcs.len(), 1);
3132         assert!(updates.update_fee.is_none());
3133         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3134         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3135         // Drop the last RAA from 3 -> 2
3136
3137         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3138         expect_pending_htlcs_forwardable!(nodes[2]);
3139         check_added_monitors!(nodes[2], 1);
3140         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3141         assert!(updates.update_add_htlcs.is_empty());
3142         assert!(updates.update_fulfill_htlcs.is_empty());
3143         assert!(updates.update_fail_malformed_htlcs.is_empty());
3144         assert_eq!(updates.update_fail_htlcs.len(), 1);
3145         assert!(updates.update_fee.is_none());
3146         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3147         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3148         check_added_monitors!(nodes[1], 1);
3149         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3150         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3151         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3152         check_added_monitors!(nodes[2], 1);
3153
3154         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3155         expect_pending_htlcs_forwardable!(nodes[2]);
3156         check_added_monitors!(nodes[2], 1);
3157         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3158         assert!(updates.update_add_htlcs.is_empty());
3159         assert!(updates.update_fulfill_htlcs.is_empty());
3160         assert!(updates.update_fail_malformed_htlcs.is_empty());
3161         assert_eq!(updates.update_fail_htlcs.len(), 1);
3162         assert!(updates.update_fee.is_none());
3163         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3164         // At this point first_payment_hash has dropped out of the latest two commitment
3165         // transactions that nodes[1] is tracking...
3166         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3167         check_added_monitors!(nodes[1], 1);
3168         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3169         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3170         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3171         check_added_monitors!(nodes[2], 1);
3172
3173         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3174         // on nodes[2]'s RAA.
3175         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3176         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3177         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3178         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3179         check_added_monitors!(nodes[1], 0);
3180
3181         if deliver_bs_raa {
3182                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3183                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3184                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3185                 check_added_monitors!(nodes[1], 1);
3186                 let events = nodes[1].node.get_and_clear_pending_events();
3187                 assert_eq!(events.len(), 1);
3188                 match events[0] {
3189                         Event::PendingHTLCsForwardable { .. } => { },
3190                         _ => panic!("Unexpected event"),
3191                 };
3192                 // Deliberately don't process the pending fail-back so they all fail back at once after
3193                 // block connection just like the !deliver_bs_raa case
3194         }
3195
3196         let mut failed_htlcs = HashSet::new();
3197         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3198
3199         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3200         check_added_monitors!(nodes[1], 1);
3201         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3202         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3203
3204         let events = nodes[1].node.get_and_clear_pending_events();
3205         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3206         match events[0] {
3207                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3208                 _ => panic!("Unexepected event"),
3209         }
3210         match events[1] {
3211                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3212                         assert_eq!(*payment_hash, fourth_payment_hash);
3213                 },
3214                 _ => panic!("Unexpected event"),
3215         }
3216         if !deliver_bs_raa {
3217                 match events[2] {
3218                         Event::PaymentFailed { ref payment_hash, .. } => {
3219                                 assert_eq!(*payment_hash, fourth_payment_hash);
3220                         },
3221                         _ => panic!("Unexpected event"),
3222                 }
3223                 match events[3] {
3224                         Event::PendingHTLCsForwardable { .. } => { },
3225                         _ => panic!("Unexpected event"),
3226                 };
3227         }
3228         nodes[1].node.process_pending_htlc_forwards();
3229         check_added_monitors!(nodes[1], 1);
3230
3231         let events = nodes[1].node.get_and_clear_pending_msg_events();
3232         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3233         match events[if deliver_bs_raa { 1 } else { 0 }] {
3234                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3235                 _ => panic!("Unexpected event"),
3236         }
3237         match events[if deliver_bs_raa { 2 } else { 1 }] {
3238                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3239                         assert_eq!(channel_id, chan_2.2);
3240                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3241                 },
3242                 _ => panic!("Unexpected event"),
3243         }
3244         if deliver_bs_raa {
3245                 match events[0] {
3246                         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, .. } } => {
3247                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3248                                 assert_eq!(update_add_htlcs.len(), 1);
3249                                 assert!(update_fulfill_htlcs.is_empty());
3250                                 assert!(update_fail_htlcs.is_empty());
3251                                 assert!(update_fail_malformed_htlcs.is_empty());
3252                         },
3253                         _ => panic!("Unexpected event"),
3254                 }
3255         }
3256         match events[if deliver_bs_raa { 3 } else { 2 }] {
3257                 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, .. } } => {
3258                         assert!(update_add_htlcs.is_empty());
3259                         assert_eq!(update_fail_htlcs.len(), 3);
3260                         assert!(update_fulfill_htlcs.is_empty());
3261                         assert!(update_fail_malformed_htlcs.is_empty());
3262                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3263
3264                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3265                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3266                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3267
3268                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3269
3270                         let events = nodes[0].node.get_and_clear_pending_events();
3271                         assert_eq!(events.len(), 3);
3272                         match events[0] {
3273                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3274                                         assert!(failed_htlcs.insert(payment_hash.0));
3275                                         // If we delivered B's RAA we got an unknown preimage error, not something
3276                                         // that we should update our routing table for.
3277                                         if !deliver_bs_raa {
3278                                                 assert!(network_update.is_some());
3279                                         }
3280                                 },
3281                                 _ => panic!("Unexpected event"),
3282                         }
3283                         match events[1] {
3284                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3285                                         assert!(failed_htlcs.insert(payment_hash.0));
3286                                         assert!(network_update.is_some());
3287                                 },
3288                                 _ => panic!("Unexpected event"),
3289                         }
3290                         match events[2] {
3291                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3292                                         assert!(failed_htlcs.insert(payment_hash.0));
3293                                         assert!(network_update.is_some());
3294                                 },
3295                                 _ => panic!("Unexpected event"),
3296                         }
3297                 },
3298                 _ => panic!("Unexpected event"),
3299         }
3300
3301         assert!(failed_htlcs.contains(&first_payment_hash.0));
3302         assert!(failed_htlcs.contains(&second_payment_hash.0));
3303         assert!(failed_htlcs.contains(&third_payment_hash.0));
3304 }
3305
3306 #[test]
3307 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3308         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3309         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3310         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3311         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3312 }
3313
3314 #[test]
3315 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3316         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3317         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3318         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3319         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3320 }
3321
3322 #[test]
3323 fn fail_backward_pending_htlc_upon_channel_failure() {
3324         let chanmon_cfgs = create_chanmon_cfgs(2);
3325         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3326         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3327         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3328         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3329
3330         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3331         {
3332                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3333                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3334                 check_added_monitors!(nodes[0], 1);
3335
3336                 let payment_event = {
3337                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3338                         assert_eq!(events.len(), 1);
3339                         SendEvent::from_event(events.remove(0))
3340                 };
3341                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3342                 assert_eq!(payment_event.msgs.len(), 1);
3343         }
3344
3345         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3346         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3347         {
3348                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3349                 check_added_monitors!(nodes[0], 0);
3350
3351                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3352         }
3353
3354         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3355         {
3356                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3357
3358                 let secp_ctx = Secp256k1::new();
3359                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3360                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3361                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3362                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3363                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3364
3365                 // Send a 0-msat update_add_htlc to fail the channel.
3366                 let update_add_htlc = msgs::UpdateAddHTLC {
3367                         channel_id: chan.2,
3368                         htlc_id: 0,
3369                         amount_msat: 0,
3370                         payment_hash,
3371                         cltv_expiry,
3372                         onion_routing_packet,
3373                 };
3374                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3375         }
3376         let events = nodes[0].node.get_and_clear_pending_events();
3377         assert_eq!(events.len(), 2);
3378         // Check that Alice fails backward the pending HTLC from the second payment.
3379         match events[0] {
3380                 Event::PaymentPathFailed { payment_hash, .. } => {
3381                         assert_eq!(payment_hash, failed_payment_hash);
3382                 },
3383                 _ => panic!("Unexpected event"),
3384         }
3385         match events[1] {
3386                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3387                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3388                 },
3389                 _ => panic!("Unexpected event {:?}", events[1]),
3390         }
3391         check_closed_broadcast!(nodes[0], true);
3392         check_added_monitors!(nodes[0], 1);
3393 }
3394
3395 #[test]
3396 fn test_htlc_ignore_latest_remote_commitment() {
3397         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3398         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3399         let chanmon_cfgs = create_chanmon_cfgs(2);
3400         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3401         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3402         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3403         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3404
3405         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3406         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3407         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3408         check_closed_broadcast!(nodes[0], true);
3409         check_added_monitors!(nodes[0], 1);
3410         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3411
3412         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3413         assert_eq!(node_txn.len(), 3);
3414         assert_eq!(node_txn[0], node_txn[1]);
3415
3416         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3417         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3418         check_closed_broadcast!(nodes[1], true);
3419         check_added_monitors!(nodes[1], 1);
3420         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3421
3422         // Duplicate the connect_block call since this may happen due to other listeners
3423         // registering new transactions
3424         header.prev_blockhash = header.block_hash();
3425         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3426 }
3427
3428 #[test]
3429 fn test_force_close_fail_back() {
3430         // Check which HTLCs are failed-backwards on channel force-closure
3431         let chanmon_cfgs = create_chanmon_cfgs(3);
3432         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3433         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3434         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3435         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3436         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3437
3438         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3439
3440         let mut payment_event = {
3441                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3442                 check_added_monitors!(nodes[0], 1);
3443
3444                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3445                 assert_eq!(events.len(), 1);
3446                 SendEvent::from_event(events.remove(0))
3447         };
3448
3449         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3450         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3451
3452         expect_pending_htlcs_forwardable!(nodes[1]);
3453
3454         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3455         assert_eq!(events_2.len(), 1);
3456         payment_event = SendEvent::from_event(events_2.remove(0));
3457         assert_eq!(payment_event.msgs.len(), 1);
3458
3459         check_added_monitors!(nodes[1], 1);
3460         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3461         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3462         check_added_monitors!(nodes[2], 1);
3463         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3464
3465         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3466         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3467         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3468
3469         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3470         check_closed_broadcast!(nodes[2], true);
3471         check_added_monitors!(nodes[2], 1);
3472         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3473         let tx = {
3474                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3475                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3476                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3477                 // back to nodes[1] upon timeout otherwise.
3478                 assert_eq!(node_txn.len(), 1);
3479                 node_txn.remove(0)
3480         };
3481
3482         mine_transaction(&nodes[1], &tx);
3483
3484         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3485         check_closed_broadcast!(nodes[1], true);
3486         check_added_monitors!(nodes[1], 1);
3487         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3488
3489         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3490         {
3491                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3492                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3493         }
3494         mine_transaction(&nodes[2], &tx);
3495         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3496         assert_eq!(node_txn.len(), 1);
3497         assert_eq!(node_txn[0].input.len(), 1);
3498         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3499         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3500         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3501
3502         check_spends!(node_txn[0], tx);
3503 }
3504
3505 #[test]
3506 fn test_dup_events_on_peer_disconnect() {
3507         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3508         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3509         // as we used to generate the event immediately upon receipt of the payment preimage in the
3510         // update_fulfill_htlc message.
3511
3512         let chanmon_cfgs = create_chanmon_cfgs(2);
3513         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3514         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3515         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3516         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3517
3518         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3519
3520         nodes[1].node.claim_funds(payment_preimage);
3521         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3522         check_added_monitors!(nodes[1], 1);
3523         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3524         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3525         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3526
3527         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3528         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3529
3530         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3531         expect_payment_path_successful!(nodes[0]);
3532 }
3533
3534 #[test]
3535 fn test_peer_disconnected_before_funding_broadcasted() {
3536         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3537         // before the funding transaction has been broadcasted.
3538         let chanmon_cfgs = create_chanmon_cfgs(2);
3539         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3540         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3541         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3542
3543         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3544         // broadcasted, even though it's created by `nodes[0]`.
3545         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();
3546         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3547         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3548         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3549         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3550
3551         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3552         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3553
3554         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3555
3556         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3557         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3558
3559         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3560         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3561         // broadcasted.
3562         {
3563                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3564         }
3565
3566         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3567         // disconnected before the funding transaction was broadcasted.
3568         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3569         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3570
3571         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3572         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3573 }
3574
3575 #[test]
3576 fn test_simple_peer_disconnect() {
3577         // Test that we can reconnect when there are no lost messages
3578         let chanmon_cfgs = create_chanmon_cfgs(3);
3579         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3580         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3581         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3582         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3583         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3584
3585         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3586         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3587         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3588
3589         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3590         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3591         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3592         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
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], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3597
3598         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3599         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3600         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3601         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).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
3606         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3607         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3608
3609         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3610         {
3611                 let events = nodes[0].node.get_and_clear_pending_events();
3612                 assert_eq!(events.len(), 3);
3613                 match events[0] {
3614                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3615                                 assert_eq!(payment_preimage, payment_preimage_3);
3616                                 assert_eq!(payment_hash, payment_hash_3);
3617                         },
3618                         _ => panic!("Unexpected event"),
3619                 }
3620                 match events[1] {
3621                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3622                                 assert_eq!(payment_hash, payment_hash_5);
3623                                 assert!(rejected_by_dest);
3624                         },
3625                         _ => panic!("Unexpected event"),
3626                 }
3627                 match events[2] {
3628                         Event::PaymentPathSuccessful { .. } => {},
3629                         _ => panic!("Unexpected event"),
3630                 }
3631         }
3632
3633         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3634         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3635 }
3636
3637 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3638         // Test that we can reconnect when in-flight HTLC updates get dropped
3639         let chanmon_cfgs = create_chanmon_cfgs(2);
3640         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3641         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3642         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3643
3644         let mut as_channel_ready = None;
3645         if messages_delivered == 0 {
3646                 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3647                 as_channel_ready = Some(channel_ready);
3648                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3649                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3650                 // it before the channel_reestablish message.
3651         } else {
3652                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3653         }
3654
3655         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3656
3657         let payment_event = {
3658                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3659                 check_added_monitors!(nodes[0], 1);
3660
3661                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3662                 assert_eq!(events.len(), 1);
3663                 SendEvent::from_event(events.remove(0))
3664         };
3665         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3666
3667         if messages_delivered < 2 {
3668                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3669         } else {
3670                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3671                 if messages_delivered >= 3 {
3672                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3673                         check_added_monitors!(nodes[1], 1);
3674                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3675
3676                         if messages_delivered >= 4 {
3677                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3678                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3679                                 check_added_monitors!(nodes[0], 1);
3680
3681                                 if messages_delivered >= 5 {
3682                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3683                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3684                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3685                                         check_added_monitors!(nodes[0], 1);
3686
3687                                         if messages_delivered >= 6 {
3688                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3689                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3690                                                 check_added_monitors!(nodes[1], 1);
3691                                         }
3692                                 }
3693                         }
3694                 }
3695         }
3696
3697         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3698         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3699         if messages_delivered < 3 {
3700                 if simulate_broken_lnd {
3701                         // lnd has a long-standing bug where they send a channel_ready prior to a
3702                         // channel_reestablish if you reconnect prior to channel_ready time.
3703                         //
3704                         // Here we simulate that behavior, delivering a channel_ready immediately on
3705                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3706                         // in `reconnect_nodes` but we currently don't fail based on that.
3707                         //
3708                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3709                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3710                 }
3711                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3712                 // received on either side, both sides will need to resend them.
3713                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3714         } else if messages_delivered == 3 {
3715                 // nodes[0] still wants its RAA + commitment_signed
3716                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3717         } else if messages_delivered == 4 {
3718                 // nodes[0] still wants its commitment_signed
3719                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3720         } else if messages_delivered == 5 {
3721                 // nodes[1] still wants its final RAA
3722                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3723         } else if messages_delivered == 6 {
3724                 // Everything was delivered...
3725                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3726         }
3727
3728         let events_1 = nodes[1].node.get_and_clear_pending_events();
3729         assert_eq!(events_1.len(), 1);
3730         match events_1[0] {
3731                 Event::PendingHTLCsForwardable { .. } => { },
3732                 _ => panic!("Unexpected event"),
3733         };
3734
3735         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3736         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3737         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3738
3739         nodes[1].node.process_pending_htlc_forwards();
3740
3741         let events_2 = nodes[1].node.get_and_clear_pending_events();
3742         assert_eq!(events_2.len(), 1);
3743         match events_2[0] {
3744                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3745                         assert_eq!(payment_hash_1, *payment_hash);
3746                         assert_eq!(amount_msat, 1_000_000);
3747                         match &purpose {
3748                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3749                                         assert!(payment_preimage.is_none());
3750                                         assert_eq!(payment_secret_1, *payment_secret);
3751                                 },
3752                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3753                         }
3754                 },
3755                 _ => panic!("Unexpected event"),
3756         }
3757
3758         nodes[1].node.claim_funds(payment_preimage_1);
3759         check_added_monitors!(nodes[1], 1);
3760         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3761
3762         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3763         assert_eq!(events_3.len(), 1);
3764         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3765                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3766                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3767                         assert!(updates.update_add_htlcs.is_empty());
3768                         assert!(updates.update_fail_htlcs.is_empty());
3769                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3770                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3771                         assert!(updates.update_fee.is_none());
3772                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3773                 },
3774                 _ => panic!("Unexpected event"),
3775         };
3776
3777         if messages_delivered >= 1 {
3778                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3779
3780                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3781                 assert_eq!(events_4.len(), 1);
3782                 match events_4[0] {
3783                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3784                                 assert_eq!(payment_preimage_1, *payment_preimage);
3785                                 assert_eq!(payment_hash_1, *payment_hash);
3786                         },
3787                         _ => panic!("Unexpected event"),
3788                 }
3789
3790                 if messages_delivered >= 2 {
3791                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3792                         check_added_monitors!(nodes[0], 1);
3793                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3794
3795                         if messages_delivered >= 3 {
3796                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3797                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3798                                 check_added_monitors!(nodes[1], 1);
3799
3800                                 if messages_delivered >= 4 {
3801                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3802                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3803                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3804                                         check_added_monitors!(nodes[1], 1);
3805
3806                                         if messages_delivered >= 5 {
3807                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3808                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3809                                                 check_added_monitors!(nodes[0], 1);
3810                                         }
3811                                 }
3812                         }
3813                 }
3814         }
3815
3816         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3817         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3818         if messages_delivered < 2 {
3819                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3820                 if messages_delivered < 1 {
3821                         expect_payment_sent!(nodes[0], payment_preimage_1);
3822                 } else {
3823                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3824                 }
3825         } else if messages_delivered == 2 {
3826                 // nodes[0] still wants its RAA + commitment_signed
3827                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3828         } else if messages_delivered == 3 {
3829                 // nodes[0] still wants its commitment_signed
3830                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3831         } else if messages_delivered == 4 {
3832                 // nodes[1] still wants its final RAA
3833                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3834         } else if messages_delivered == 5 {
3835                 // Everything was delivered...
3836                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3837         }
3838
3839         if messages_delivered == 1 || messages_delivered == 2 {
3840                 expect_payment_path_successful!(nodes[0]);
3841         }
3842
3843         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3844         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3845         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3846
3847         if messages_delivered > 2 {
3848                 expect_payment_path_successful!(nodes[0]);
3849         }
3850
3851         // Channel should still work fine...
3852         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3853         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3854         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3855 }
3856
3857 #[test]
3858 fn test_drop_messages_peer_disconnect_a() {
3859         do_test_drop_messages_peer_disconnect(0, true);
3860         do_test_drop_messages_peer_disconnect(0, false);
3861         do_test_drop_messages_peer_disconnect(1, false);
3862         do_test_drop_messages_peer_disconnect(2, false);
3863 }
3864
3865 #[test]
3866 fn test_drop_messages_peer_disconnect_b() {
3867         do_test_drop_messages_peer_disconnect(3, false);
3868         do_test_drop_messages_peer_disconnect(4, false);
3869         do_test_drop_messages_peer_disconnect(5, false);
3870         do_test_drop_messages_peer_disconnect(6, false);
3871 }
3872
3873 #[test]
3874 fn test_funding_peer_disconnect() {
3875         // Test that we can lock in our funding tx while disconnected
3876         let chanmon_cfgs = create_chanmon_cfgs(2);
3877         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3878         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3879         let persister: test_utils::TestPersister;
3880         let new_chain_monitor: test_utils::TestChainMonitor;
3881         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3882         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3883         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3884
3885         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3886         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3887
3888         confirm_transaction(&nodes[0], &tx);
3889         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3890         assert!(events_1.is_empty());
3891
3892         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
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[1], &tx);
3898         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3899         assert!(events_2.is_empty());
3900
3901         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3902         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3903         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3904         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3905
3906         // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3907         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3908         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3909         assert_eq!(events_3.len(), 1);
3910         let as_channel_ready = match events_3[0] {
3911                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3912                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3913                         msg.clone()
3914                 },
3915                 _ => panic!("Unexpected event {:?}", events_3[0]),
3916         };
3917
3918         // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3919         // announcement_signatures as well as channel_update.
3920         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3921         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3922         assert_eq!(events_4.len(), 3);
3923         let chan_id;
3924         let bs_channel_ready = match events_4[0] {
3925                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3926                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3927                         chan_id = msg.channel_id;
3928                         msg.clone()
3929                 },
3930                 _ => panic!("Unexpected event {:?}", events_4[0]),
3931         };
3932         let bs_announcement_sigs = match events_4[1] {
3933                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3934                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3935                         msg.clone()
3936                 },
3937                 _ => panic!("Unexpected event {:?}", events_4[1]),
3938         };
3939         match events_4[2] {
3940                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3941                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3942                 },
3943                 _ => panic!("Unexpected event {:?}", events_4[2]),
3944         }
3945
3946         // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3947         // generates a duplicative private channel_update
3948         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3949         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3950         assert_eq!(events_5.len(), 1);
3951         match events_5[0] {
3952                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3953                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3954                 },
3955                 _ => panic!("Unexpected event {:?}", events_5[0]),
3956         };
3957
3958         // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3959         // announcement_signatures.
3960         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3961         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3962         assert_eq!(events_6.len(), 1);
3963         let as_announcement_sigs = match events_6[0] {
3964                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3965                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3966                         msg.clone()
3967                 },
3968                 _ => panic!("Unexpected event {:?}", events_6[0]),
3969         };
3970
3971         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3972         // broadcast the channel announcement globally, as well as re-send its (now-public)
3973         // channel_update.
3974         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3975         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3976         assert_eq!(events_7.len(), 1);
3977         let (chan_announcement, as_update) = match events_7[0] {
3978                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3979                         (msg.clone(), update_msg.clone())
3980                 },
3981                 _ => panic!("Unexpected event {:?}", events_7[0]),
3982         };
3983
3984         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3985         // same channel_announcement.
3986         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3987         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3988         assert_eq!(events_8.len(), 1);
3989         let bs_update = match events_8[0] {
3990                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3991                         assert_eq!(*msg, chan_announcement);
3992                         update_msg.clone()
3993                 },
3994                 _ => panic!("Unexpected event {:?}", events_8[0]),
3995         };
3996
3997         // Provide the channel announcement and public updates to the network graph
3998         nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3999         nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
4000         nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
4001
4002         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4003         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4004         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
4005
4006         // Check that after deserialization and reconnection we can still generate an identical
4007         // channel_announcement from the cached signatures.
4008         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4009
4010         let nodes_0_serialized = nodes[0].node.encode();
4011         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4012         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4013
4014         persister = test_utils::TestPersister::new();
4015         let keys_manager = &chanmon_cfgs[0].keys_manager;
4016         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);
4017         nodes[0].chain_monitor = &new_chain_monitor;
4018         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4019         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4020                 &mut chan_0_monitor_read, keys_manager).unwrap();
4021         assert!(chan_0_monitor_read.is_empty());
4022
4023         let mut nodes_0_read = &nodes_0_serialized[..];
4024         let (_, nodes_0_deserialized_tmp) = {
4025                 let mut channel_monitors = HashMap::new();
4026                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4027                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4028                         default_config: UserConfig::default(),
4029                         keys_manager,
4030                         fee_estimator: node_cfgs[0].fee_estimator,
4031                         chain_monitor: nodes[0].chain_monitor,
4032                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4033                         logger: nodes[0].logger,
4034                         channel_monitors,
4035                 }).unwrap()
4036         };
4037         nodes_0_deserialized = nodes_0_deserialized_tmp;
4038         assert!(nodes_0_read.is_empty());
4039
4040         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4041         nodes[0].node = &nodes_0_deserialized;
4042         check_added_monitors!(nodes[0], 1);
4043
4044         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4045
4046         // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4047         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4048         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4049         let mut found_announcement = false;
4050         for event in msgs.iter() {
4051                 match event {
4052                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4053                                 if *msg == chan_announcement { found_announcement = true; }
4054                         },
4055                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4056                         _ => panic!("Unexpected event"),
4057                 }
4058         }
4059         assert!(found_announcement);
4060 }
4061
4062 #[test]
4063 fn test_channel_ready_without_best_block_updated() {
4064         // Previously, if we were offline when a funding transaction was locked in, and then we came
4065         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4066         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4067         // channel_ready immediately instead.
4068         let chanmon_cfgs = create_chanmon_cfgs(2);
4069         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4070         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4071         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4072         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4073
4074         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4075
4076         let conf_height = nodes[0].best_block_info().1 + 1;
4077         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4078         let block_txn = [funding_tx];
4079         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4080         let conf_block_header = nodes[0].get_block_header(conf_height);
4081         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4082
4083         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4084         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4085         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4086 }
4087
4088 #[test]
4089 fn test_drop_messages_peer_disconnect_dual_htlc() {
4090         // Test that we can handle reconnecting when both sides of a channel have pending
4091         // commitment_updates when we disconnect.
4092         let chanmon_cfgs = create_chanmon_cfgs(2);
4093         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4094         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4095         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4096         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4097
4098         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4099
4100         // Now try to send a second payment which will fail to send
4101         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4102         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4103         check_added_monitors!(nodes[0], 1);
4104
4105         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4106         assert_eq!(events_1.len(), 1);
4107         match events_1[0] {
4108                 MessageSendEvent::UpdateHTLCs { .. } => {},
4109                 _ => panic!("Unexpected event"),
4110         }
4111
4112         nodes[1].node.claim_funds(payment_preimage_1);
4113         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4114         check_added_monitors!(nodes[1], 1);
4115
4116         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4117         assert_eq!(events_2.len(), 1);
4118         match events_2[0] {
4119                 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 } } => {
4120                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4121                         assert!(update_add_htlcs.is_empty());
4122                         assert_eq!(update_fulfill_htlcs.len(), 1);
4123                         assert!(update_fail_htlcs.is_empty());
4124                         assert!(update_fail_malformed_htlcs.is_empty());
4125                         assert!(update_fee.is_none());
4126
4127                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4128                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4129                         assert_eq!(events_3.len(), 1);
4130                         match events_3[0] {
4131                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4132                                         assert_eq!(*payment_preimage, payment_preimage_1);
4133                                         assert_eq!(*payment_hash, payment_hash_1);
4134                                 },
4135                                 _ => panic!("Unexpected event"),
4136                         }
4137
4138                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4139                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4140                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4141                         check_added_monitors!(nodes[0], 1);
4142                 },
4143                 _ => panic!("Unexpected event"),
4144         }
4145
4146         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4147         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4148
4149         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4150         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4151         assert_eq!(reestablish_1.len(), 1);
4152         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4153         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4154         assert_eq!(reestablish_2.len(), 1);
4155
4156         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4157         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4158         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4159         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4160
4161         assert!(as_resp.0.is_none());
4162         assert!(bs_resp.0.is_none());
4163
4164         assert!(bs_resp.1.is_none());
4165         assert!(bs_resp.2.is_none());
4166
4167         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4168
4169         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4170         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4171         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4172         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4173         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4174         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4175         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4176         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4177         // No commitment_signed so get_event_msg's assert(len == 1) passes
4178         check_added_monitors!(nodes[1], 1);
4179
4180         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4181         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4182         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4183         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4184         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4185         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4186         assert!(bs_second_commitment_signed.update_fee.is_none());
4187         check_added_monitors!(nodes[1], 1);
4188
4189         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4190         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4191         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4192         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4193         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4194         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4195         assert!(as_commitment_signed.update_fee.is_none());
4196         check_added_monitors!(nodes[0], 1);
4197
4198         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4199         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4200         // No commitment_signed so get_event_msg's assert(len == 1) passes
4201         check_added_monitors!(nodes[0], 1);
4202
4203         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4204         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4205         // No commitment_signed so get_event_msg's assert(len == 1) passes
4206         check_added_monitors!(nodes[1], 1);
4207
4208         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4209         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4210         check_added_monitors!(nodes[1], 1);
4211
4212         expect_pending_htlcs_forwardable!(nodes[1]);
4213
4214         let events_5 = nodes[1].node.get_and_clear_pending_events();
4215         assert_eq!(events_5.len(), 1);
4216         match events_5[0] {
4217                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4218                         assert_eq!(payment_hash_2, *payment_hash);
4219                         match &purpose {
4220                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4221                                         assert!(payment_preimage.is_none());
4222                                         assert_eq!(payment_secret_2, *payment_secret);
4223                                 },
4224                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4225                         }
4226                 },
4227                 _ => panic!("Unexpected event"),
4228         }
4229
4230         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4231         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4232         check_added_monitors!(nodes[0], 1);
4233
4234         expect_payment_path_successful!(nodes[0]);
4235         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4236 }
4237
4238 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4239         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4240         // to avoid our counterparty failing the channel.
4241         let chanmon_cfgs = create_chanmon_cfgs(2);
4242         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4243         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4244         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4245
4246         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4247
4248         let our_payment_hash = if send_partial_mpp {
4249                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4250                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4251                 // indicates there are more HTLCs coming.
4252                 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.
4253                 let payment_id = PaymentId([42; 32]);
4254                 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();
4255                 check_added_monitors!(nodes[0], 1);
4256                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4257                 assert_eq!(events.len(), 1);
4258                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4259                 // hop should *not* yet generate any PaymentReceived event(s).
4260                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4261                 our_payment_hash
4262         } else {
4263                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4264         };
4265
4266         let mut block = Block {
4267                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4268                 txdata: vec![],
4269         };
4270         connect_block(&nodes[0], &block);
4271         connect_block(&nodes[1], &block);
4272         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4273         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4274                 block.header.prev_blockhash = block.block_hash();
4275                 connect_block(&nodes[0], &block);
4276                 connect_block(&nodes[1], &block);
4277         }
4278
4279         expect_pending_htlcs_forwardable!(nodes[1]);
4280
4281         check_added_monitors!(nodes[1], 1);
4282         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4283         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4284         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4285         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4286         assert!(htlc_timeout_updates.update_fee.is_none());
4287
4288         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4289         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4290         // 100_000 msat as u64, followed by the height at which we failed back above
4291         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4292         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4293         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4294 }
4295
4296 #[test]
4297 fn test_htlc_timeout() {
4298         do_test_htlc_timeout(true);
4299         do_test_htlc_timeout(false);
4300 }
4301
4302 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4303         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4304         let chanmon_cfgs = create_chanmon_cfgs(3);
4305         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4306         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4307         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4308         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4309         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4310
4311         // Make sure all nodes are at the same starting height
4312         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4313         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4314         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4315
4316         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4317         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4318         {
4319                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4320         }
4321         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4322         check_added_monitors!(nodes[1], 1);
4323
4324         // Now attempt to route a second payment, which should be placed in the holding cell
4325         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4326         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4327         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4328         if forwarded_htlc {
4329                 check_added_monitors!(nodes[0], 1);
4330                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4331                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4332                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4333                 expect_pending_htlcs_forwardable!(nodes[1]);
4334         }
4335         check_added_monitors!(nodes[1], 0);
4336
4337         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4338         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4339         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4340         connect_blocks(&nodes[1], 1);
4341
4342         if forwarded_htlc {
4343                 expect_pending_htlcs_forwardable!(nodes[1]);
4344                 check_added_monitors!(nodes[1], 1);
4345                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4346                 assert_eq!(fail_commit.len(), 1);
4347                 match fail_commit[0] {
4348                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4349                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4350                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4351                         },
4352                         _ => unreachable!(),
4353                 }
4354                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4355         } else {
4356                 let events = nodes[1].node.get_and_clear_pending_events();
4357                 assert_eq!(events.len(), 2);
4358                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4359                         assert_eq!(*payment_hash, second_payment_hash);
4360                 } else { panic!("Unexpected event"); }
4361                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4362                         assert_eq!(*payment_hash, second_payment_hash);
4363                 } else { panic!("Unexpected event"); }
4364         }
4365 }
4366
4367 #[test]
4368 fn test_holding_cell_htlc_add_timeouts() {
4369         do_test_holding_cell_htlc_add_timeouts(false);
4370         do_test_holding_cell_htlc_add_timeouts(true);
4371 }
4372
4373 #[test]
4374 fn test_no_txn_manager_serialize_deserialize() {
4375         let chanmon_cfgs = create_chanmon_cfgs(2);
4376         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4377         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4378         let logger: test_utils::TestLogger;
4379         let fee_estimator: test_utils::TestFeeEstimator;
4380         let persister: test_utils::TestPersister;
4381         let new_chain_monitor: test_utils::TestChainMonitor;
4382         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4383         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4384
4385         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4386
4387         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4388
4389         let nodes_0_serialized = nodes[0].node.encode();
4390         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4391         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4392                 .write(&mut chan_0_monitor_serialized).unwrap();
4393
4394         logger = test_utils::TestLogger::new();
4395         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4396         persister = test_utils::TestPersister::new();
4397         let keys_manager = &chanmon_cfgs[0].keys_manager;
4398         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4399         nodes[0].chain_monitor = &new_chain_monitor;
4400         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4401         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4402                 &mut chan_0_monitor_read, keys_manager).unwrap();
4403         assert!(chan_0_monitor_read.is_empty());
4404
4405         let mut nodes_0_read = &nodes_0_serialized[..];
4406         let config = UserConfig::default();
4407         let (_, nodes_0_deserialized_tmp) = {
4408                 let mut channel_monitors = HashMap::new();
4409                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4410                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4411                         default_config: config,
4412                         keys_manager,
4413                         fee_estimator: &fee_estimator,
4414                         chain_monitor: nodes[0].chain_monitor,
4415                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4416                         logger: &logger,
4417                         channel_monitors,
4418                 }).unwrap()
4419         };
4420         nodes_0_deserialized = nodes_0_deserialized_tmp;
4421         assert!(nodes_0_read.is_empty());
4422
4423         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4424         nodes[0].node = &nodes_0_deserialized;
4425         assert_eq!(nodes[0].node.list_channels().len(), 1);
4426         check_added_monitors!(nodes[0], 1);
4427
4428         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4429         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4430         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4431         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4432
4433         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4434         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4435         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4436         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4437
4438         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4439         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4440         for node in nodes.iter() {
4441                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4442                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4443                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4444         }
4445
4446         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4447 }
4448
4449 #[test]
4450 fn test_manager_serialize_deserialize_events() {
4451         // This test makes sure the events field in ChannelManager survives de/serialization
4452         let chanmon_cfgs = create_chanmon_cfgs(2);
4453         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4454         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4455         let fee_estimator: test_utils::TestFeeEstimator;
4456         let persister: test_utils::TestPersister;
4457         let logger: test_utils::TestLogger;
4458         let new_chain_monitor: test_utils::TestChainMonitor;
4459         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4460         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4461
4462         // Start creating a channel, but stop right before broadcasting the funding transaction
4463         let channel_value = 100000;
4464         let push_msat = 10001;
4465         let a_flags = InitFeatures::known();
4466         let b_flags = InitFeatures::known();
4467         let node_a = nodes.remove(0);
4468         let node_b = nodes.remove(0);
4469         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4470         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()));
4471         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()));
4472
4473         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4474
4475         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4476         check_added_monitors!(node_a, 0);
4477
4478         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()));
4479         {
4480                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4481                 assert_eq!(added_monitors.len(), 1);
4482                 assert_eq!(added_monitors[0].0, funding_output);
4483                 added_monitors.clear();
4484         }
4485
4486         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4487         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4488         {
4489                 let mut added_monitors = node_a.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         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4495
4496         nodes.push(node_a);
4497         nodes.push(node_b);
4498
4499         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4500         let nodes_0_serialized = nodes[0].node.encode();
4501         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4502         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4503
4504         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4505         logger = test_utils::TestLogger::new();
4506         persister = test_utils::TestPersister::new();
4507         let keys_manager = &chanmon_cfgs[0].keys_manager;
4508         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4509         nodes[0].chain_monitor = &new_chain_monitor;
4510         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4511         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4512                 &mut chan_0_monitor_read, keys_manager).unwrap();
4513         assert!(chan_0_monitor_read.is_empty());
4514
4515         let mut nodes_0_read = &nodes_0_serialized[..];
4516         let config = UserConfig::default();
4517         let (_, nodes_0_deserialized_tmp) = {
4518                 let mut channel_monitors = HashMap::new();
4519                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4520                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4521                         default_config: config,
4522                         keys_manager,
4523                         fee_estimator: &fee_estimator,
4524                         chain_monitor: nodes[0].chain_monitor,
4525                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4526                         logger: &logger,
4527                         channel_monitors,
4528                 }).unwrap()
4529         };
4530         nodes_0_deserialized = nodes_0_deserialized_tmp;
4531         assert!(nodes_0_read.is_empty());
4532
4533         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4534
4535         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4536         nodes[0].node = &nodes_0_deserialized;
4537
4538         // After deserializing, make sure the funding_transaction is still held by the channel manager
4539         let events_4 = nodes[0].node.get_and_clear_pending_events();
4540         assert_eq!(events_4.len(), 0);
4541         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4542         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4543
4544         // Make sure the channel is functioning as though the de/serialization never happened
4545         assert_eq!(nodes[0].node.list_channels().len(), 1);
4546         check_added_monitors!(nodes[0], 1);
4547
4548         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4549         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4550         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4551         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4552
4553         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4554         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4555         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4556         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4557
4558         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4559         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4560         for node in nodes.iter() {
4561                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4562                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4563                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4564         }
4565
4566         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4567 }
4568
4569 #[test]
4570 fn test_simple_manager_serialize_deserialize() {
4571         let chanmon_cfgs = create_chanmon_cfgs(2);
4572         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4573         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4574         let logger: test_utils::TestLogger;
4575         let fee_estimator: test_utils::TestFeeEstimator;
4576         let persister: test_utils::TestPersister;
4577         let new_chain_monitor: test_utils::TestChainMonitor;
4578         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4579         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4580         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4581
4582         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4583         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4584
4585         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4586
4587         let nodes_0_serialized = nodes[0].node.encode();
4588         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4589         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4590
4591         logger = test_utils::TestLogger::new();
4592         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4593         persister = test_utils::TestPersister::new();
4594         let keys_manager = &chanmon_cfgs[0].keys_manager;
4595         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4596         nodes[0].chain_monitor = &new_chain_monitor;
4597         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4598         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4599                 &mut chan_0_monitor_read, keys_manager).unwrap();
4600         assert!(chan_0_monitor_read.is_empty());
4601
4602         let mut nodes_0_read = &nodes_0_serialized[..];
4603         let (_, nodes_0_deserialized_tmp) = {
4604                 let mut channel_monitors = HashMap::new();
4605                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4606                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4607                         default_config: UserConfig::default(),
4608                         keys_manager,
4609                         fee_estimator: &fee_estimator,
4610                         chain_monitor: nodes[0].chain_monitor,
4611                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4612                         logger: &logger,
4613                         channel_monitors,
4614                 }).unwrap()
4615         };
4616         nodes_0_deserialized = nodes_0_deserialized_tmp;
4617         assert!(nodes_0_read.is_empty());
4618
4619         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4620         nodes[0].node = &nodes_0_deserialized;
4621         check_added_monitors!(nodes[0], 1);
4622
4623         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4624
4625         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4626         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4627 }
4628
4629 #[test]
4630 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4631         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4632         let chanmon_cfgs = create_chanmon_cfgs(4);
4633         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4634         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4635         let logger: test_utils::TestLogger;
4636         let fee_estimator: test_utils::TestFeeEstimator;
4637         let persister: test_utils::TestPersister;
4638         let new_chain_monitor: test_utils::TestChainMonitor;
4639         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4640         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4641         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4642         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4643         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4644
4645         let mut node_0_stale_monitors_serialized = Vec::new();
4646         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4647                 let mut writer = test_utils::TestVecWriter(Vec::new());
4648                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4649                 node_0_stale_monitors_serialized.push(writer.0);
4650         }
4651
4652         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4653
4654         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4655         let nodes_0_serialized = nodes[0].node.encode();
4656
4657         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4658         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4659         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4660         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4661
4662         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4663         // nodes[3])
4664         let mut node_0_monitors_serialized = Vec::new();
4665         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4666                 let mut writer = test_utils::TestVecWriter(Vec::new());
4667                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4668                 node_0_monitors_serialized.push(writer.0);
4669         }
4670
4671         logger = test_utils::TestLogger::new();
4672         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4673         persister = test_utils::TestPersister::new();
4674         let keys_manager = &chanmon_cfgs[0].keys_manager;
4675         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4676         nodes[0].chain_monitor = &new_chain_monitor;
4677
4678
4679         let mut node_0_stale_monitors = Vec::new();
4680         for serialized in node_0_stale_monitors_serialized.iter() {
4681                 let mut read = &serialized[..];
4682                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4683                 assert!(read.is_empty());
4684                 node_0_stale_monitors.push(monitor);
4685         }
4686
4687         let mut node_0_monitors = Vec::new();
4688         for serialized in node_0_monitors_serialized.iter() {
4689                 let mut read = &serialized[..];
4690                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4691                 assert!(read.is_empty());
4692                 node_0_monitors.push(monitor);
4693         }
4694
4695         let mut nodes_0_read = &nodes_0_serialized[..];
4696         if let Err(msgs::DecodeError::InvalidValue) =
4697                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4698                 default_config: UserConfig::default(),
4699                 keys_manager,
4700                 fee_estimator: &fee_estimator,
4701                 chain_monitor: nodes[0].chain_monitor,
4702                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4703                 logger: &logger,
4704                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4705         }) { } else {
4706                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4707         };
4708
4709         let mut nodes_0_read = &nodes_0_serialized[..];
4710         let (_, nodes_0_deserialized_tmp) =
4711                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4712                 default_config: UserConfig::default(),
4713                 keys_manager,
4714                 fee_estimator: &fee_estimator,
4715                 chain_monitor: nodes[0].chain_monitor,
4716                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4717                 logger: &logger,
4718                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4719         }).unwrap();
4720         nodes_0_deserialized = nodes_0_deserialized_tmp;
4721         assert!(nodes_0_read.is_empty());
4722
4723         { // Channel close should result in a commitment tx
4724                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4725                 assert_eq!(txn.len(), 1);
4726                 check_spends!(txn[0], funding_tx);
4727                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4728         }
4729
4730         for monitor in node_0_monitors.drain(..) {
4731                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4732                 check_added_monitors!(nodes[0], 1);
4733         }
4734         nodes[0].node = &nodes_0_deserialized;
4735         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4736
4737         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4738         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4739         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4740         //... and we can even still claim the payment!
4741         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4742
4743         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4744         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4745         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4746         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4747         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4748         assert_eq!(msg_events.len(), 1);
4749         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4750                 match action {
4751                         &ErrorAction::SendErrorMessage { ref msg } => {
4752                                 assert_eq!(msg.channel_id, channel_id);
4753                         },
4754                         _ => panic!("Unexpected event!"),
4755                 }
4756         }
4757 }
4758
4759 macro_rules! check_spendable_outputs {
4760         ($node: expr, $keysinterface: expr) => {
4761                 {
4762                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4763                         let mut txn = Vec::new();
4764                         let mut all_outputs = Vec::new();
4765                         let secp_ctx = Secp256k1::new();
4766                         for event in events.drain(..) {
4767                                 match event {
4768                                         Event::SpendableOutputs { mut outputs } => {
4769                                                 for outp in outputs.drain(..) {
4770                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4771                                                         all_outputs.push(outp);
4772                                                 }
4773                                         },
4774                                         _ => panic!("Unexpected event"),
4775                                 };
4776                         }
4777                         if all_outputs.len() > 1 {
4778                                 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) {
4779                                         txn.push(tx);
4780                                 }
4781                         }
4782                         txn
4783                 }
4784         }
4785 }
4786
4787 #[test]
4788 fn test_claim_sizeable_push_msat() {
4789         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4790         let chanmon_cfgs = create_chanmon_cfgs(2);
4791         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4792         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4793         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4794
4795         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4796         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4797         check_closed_broadcast!(nodes[1], true);
4798         check_added_monitors!(nodes[1], 1);
4799         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4800         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4801         assert_eq!(node_txn.len(), 1);
4802         check_spends!(node_txn[0], chan.3);
4803         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
4804
4805         mine_transaction(&nodes[1], &node_txn[0]);
4806         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4807
4808         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4809         assert_eq!(spend_txn.len(), 1);
4810         assert_eq!(spend_txn[0].input.len(), 1);
4811         check_spends!(spend_txn[0], node_txn[0]);
4812         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4813 }
4814
4815 #[test]
4816 fn test_claim_on_remote_sizeable_push_msat() {
4817         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4818         // to_remote output is encumbered by a P2WPKH
4819         let chanmon_cfgs = create_chanmon_cfgs(2);
4820         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4821         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4822         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4823
4824         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4825         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4826         check_closed_broadcast!(nodes[0], true);
4827         check_added_monitors!(nodes[0], 1);
4828         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4829
4830         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4831         assert_eq!(node_txn.len(), 1);
4832         check_spends!(node_txn[0], chan.3);
4833         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
4834
4835         mine_transaction(&nodes[1], &node_txn[0]);
4836         check_closed_broadcast!(nodes[1], true);
4837         check_added_monitors!(nodes[1], 1);
4838         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4839         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4840
4841         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4842         assert_eq!(spend_txn.len(), 1);
4843         check_spends!(spend_txn[0], node_txn[0]);
4844 }
4845
4846 #[test]
4847 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4848         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4849         // to_remote output is encumbered by a P2WPKH
4850
4851         let chanmon_cfgs = create_chanmon_cfgs(2);
4852         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4853         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4854         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4855
4856         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4857         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4858         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4859         assert_eq!(revoked_local_txn[0].input.len(), 1);
4860         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4861
4862         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4863         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4864         check_closed_broadcast!(nodes[1], true);
4865         check_added_monitors!(nodes[1], 1);
4866         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4867
4868         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4869         mine_transaction(&nodes[1], &node_txn[0]);
4870         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4871
4872         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4873         assert_eq!(spend_txn.len(), 3);
4874         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4875         check_spends!(spend_txn[1], node_txn[0]);
4876         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4877 }
4878
4879 #[test]
4880 fn test_static_spendable_outputs_preimage_tx() {
4881         let chanmon_cfgs = create_chanmon_cfgs(2);
4882         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4883         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4884         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4885
4886         // Create some initial channels
4887         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4888
4889         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4890
4891         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4892         assert_eq!(commitment_tx[0].input.len(), 1);
4893         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4894
4895         // Settle A's commitment tx on B's chain
4896         nodes[1].node.claim_funds(payment_preimage);
4897         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4898         check_added_monitors!(nodes[1], 1);
4899         mine_transaction(&nodes[1], &commitment_tx[0]);
4900         check_added_monitors!(nodes[1], 1);
4901         let events = nodes[1].node.get_and_clear_pending_msg_events();
4902         match events[0] {
4903                 MessageSendEvent::UpdateHTLCs { .. } => {},
4904                 _ => panic!("Unexpected event"),
4905         }
4906         match events[1] {
4907                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4908                 _ => panic!("Unexepected event"),
4909         }
4910
4911         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4912         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4913         assert_eq!(node_txn.len(), 3);
4914         check_spends!(node_txn[0], commitment_tx[0]);
4915         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4916         check_spends!(node_txn[1], chan_1.3);
4917         check_spends!(node_txn[2], node_txn[1]);
4918
4919         mine_transaction(&nodes[1], &node_txn[0]);
4920         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4921         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4922
4923         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4924         assert_eq!(spend_txn.len(), 1);
4925         check_spends!(spend_txn[0], node_txn[0]);
4926 }
4927
4928 #[test]
4929 fn test_static_spendable_outputs_timeout_tx() {
4930         let chanmon_cfgs = create_chanmon_cfgs(2);
4931         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4932         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4933         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4934
4935         // Create some initial channels
4936         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4937
4938         // Rebalance the network a bit by relaying one payment through all the channels ...
4939         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4940
4941         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4942
4943         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4944         assert_eq!(commitment_tx[0].input.len(), 1);
4945         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4946
4947         // Settle A's commitment tx on B' chain
4948         mine_transaction(&nodes[1], &commitment_tx[0]);
4949         check_added_monitors!(nodes[1], 1);
4950         let events = nodes[1].node.get_and_clear_pending_msg_events();
4951         match events[0] {
4952                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4953                 _ => panic!("Unexpected event"),
4954         }
4955         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4956
4957         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4958         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4959         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4960         check_spends!(node_txn[0], chan_1.3.clone());
4961         check_spends!(node_txn[1],  commitment_tx[0].clone());
4962         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4963
4964         mine_transaction(&nodes[1], &node_txn[1]);
4965         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4966         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4967         expect_payment_failed!(nodes[1], our_payment_hash, true);
4968
4969         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4970         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4971         check_spends!(spend_txn[0], commitment_tx[0]);
4972         check_spends!(spend_txn[1], node_txn[1]);
4973         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4974 }
4975
4976 #[test]
4977 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4978         let chanmon_cfgs = create_chanmon_cfgs(2);
4979         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4980         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4981         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4982
4983         // Create some initial channels
4984         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4985
4986         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4987         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4988         assert_eq!(revoked_local_txn[0].input.len(), 1);
4989         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4990
4991         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4992
4993         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4994         check_closed_broadcast!(nodes[1], true);
4995         check_added_monitors!(nodes[1], 1);
4996         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4997
4998         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4999         assert_eq!(node_txn.len(), 2);
5000         assert_eq!(node_txn[0].input.len(), 2);
5001         check_spends!(node_txn[0], revoked_local_txn[0]);
5002
5003         mine_transaction(&nodes[1], &node_txn[0]);
5004         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5005
5006         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5007         assert_eq!(spend_txn.len(), 1);
5008         check_spends!(spend_txn[0], node_txn[0]);
5009 }
5010
5011 #[test]
5012 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5013         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5014         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5015         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5016         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5017         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5018
5019         // Create some initial channels
5020         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5021
5022         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5023         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5024         assert_eq!(revoked_local_txn[0].input.len(), 1);
5025         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5026
5027         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5028
5029         // A will generate HTLC-Timeout from revoked commitment tx
5030         mine_transaction(&nodes[0], &revoked_local_txn[0]);
5031         check_closed_broadcast!(nodes[0], true);
5032         check_added_monitors!(nodes[0], 1);
5033         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5034         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5035
5036         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5037         assert_eq!(revoked_htlc_txn.len(), 2);
5038         check_spends!(revoked_htlc_txn[0], chan_1.3);
5039         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5040         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5041         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5042         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5043
5044         // B will generate justice tx from A's revoked commitment/HTLC tx
5045         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5046         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5047         check_closed_broadcast!(nodes[1], true);
5048         check_added_monitors!(nodes[1], 1);
5049         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5050
5051         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5052         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5053         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5054         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5055         // transactions next...
5056         assert_eq!(node_txn[0].input.len(), 3);
5057         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5058
5059         assert_eq!(node_txn[1].input.len(), 2);
5060         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5061         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5062                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5063         } else {
5064                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5065                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5066         }
5067
5068         assert_eq!(node_txn[2].input.len(), 1);
5069         check_spends!(node_txn[2], chan_1.3);
5070
5071         mine_transaction(&nodes[1], &node_txn[1]);
5072         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5073
5074         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5075         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5076         assert_eq!(spend_txn.len(), 1);
5077         assert_eq!(spend_txn[0].input.len(), 1);
5078         check_spends!(spend_txn[0], node_txn[1]);
5079 }
5080
5081 #[test]
5082 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5083         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5084         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5085         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5086         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5087         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5088
5089         // Create some initial channels
5090         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5091
5092         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5093         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5094         assert_eq!(revoked_local_txn[0].input.len(), 1);
5095         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5096
5097         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5098         assert_eq!(revoked_local_txn[0].output.len(), 2);
5099
5100         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5101
5102         // B will generate HTLC-Success from revoked commitment tx
5103         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5104         check_closed_broadcast!(nodes[1], true);
5105         check_added_monitors!(nodes[1], 1);
5106         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5107         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5108
5109         assert_eq!(revoked_htlc_txn.len(), 2);
5110         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5111         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5112         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5113
5114         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5115         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5116         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5117
5118         // A will generate justice tx from B's revoked commitment/HTLC tx
5119         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5120         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5121         check_closed_broadcast!(nodes[0], true);
5122         check_added_monitors!(nodes[0], 1);
5123         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5124
5125         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5126         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5127
5128         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5129         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5130         // transactions next...
5131         assert_eq!(node_txn[0].input.len(), 2);
5132         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5133         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5134                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5135         } else {
5136                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5137                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5138         }
5139
5140         assert_eq!(node_txn[1].input.len(), 1);
5141         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5142
5143         check_spends!(node_txn[2], chan_1.3);
5144
5145         mine_transaction(&nodes[0], &node_txn[1]);
5146         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5147
5148         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5149         // didn't try to generate any new transactions.
5150
5151         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5152         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5153         assert_eq!(spend_txn.len(), 3);
5154         assert_eq!(spend_txn[0].input.len(), 1);
5155         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5156         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5157         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5158         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5159 }
5160
5161 #[test]
5162 fn test_onchain_to_onchain_claim() {
5163         // Test that in case of channel closure, we detect the state of output and claim HTLC
5164         // on downstream peer's remote commitment tx.
5165         // First, have C claim an HTLC against its own latest commitment transaction.
5166         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5167         // channel.
5168         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5169         // gets broadcast.
5170
5171         let chanmon_cfgs = create_chanmon_cfgs(3);
5172         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5173         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5174         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5175
5176         // Create some initial channels
5177         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5178         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5179
5180         // Ensure all nodes are at the same height
5181         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5182         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5183         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5184         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5185
5186         // Rebalance the network a bit by relaying one payment through all the channels ...
5187         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5188         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5189
5190         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5191         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5192         check_spends!(commitment_tx[0], chan_2.3);
5193         nodes[2].node.claim_funds(payment_preimage);
5194         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5195         check_added_monitors!(nodes[2], 1);
5196         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5197         assert!(updates.update_add_htlcs.is_empty());
5198         assert!(updates.update_fail_htlcs.is_empty());
5199         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5200         assert!(updates.update_fail_malformed_htlcs.is_empty());
5201
5202         mine_transaction(&nodes[2], &commitment_tx[0]);
5203         check_closed_broadcast!(nodes[2], true);
5204         check_added_monitors!(nodes[2], 1);
5205         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5206
5207         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5208         assert_eq!(c_txn.len(), 3);
5209         assert_eq!(c_txn[0], c_txn[2]);
5210         assert_eq!(commitment_tx[0], c_txn[1]);
5211         check_spends!(c_txn[1], chan_2.3);
5212         check_spends!(c_txn[2], c_txn[1]);
5213         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5214         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5215         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5216         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5217
5218         // 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
5219         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5220         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5221         check_added_monitors!(nodes[1], 1);
5222         let events = nodes[1].node.get_and_clear_pending_events();
5223         assert_eq!(events.len(), 2);
5224         match events[0] {
5225                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5226                 _ => panic!("Unexpected event"),
5227         }
5228         match events[1] {
5229                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5230                         assert_eq!(fee_earned_msat, Some(1000));
5231                         assert_eq!(prev_channel_id, Some(chan_1.2));
5232                         assert_eq!(claim_from_onchain_tx, true);
5233                         assert_eq!(next_channel_id, Some(chan_2.2));
5234                 },
5235                 _ => panic!("Unexpected event"),
5236         }
5237         {
5238                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5239                 // ChannelMonitor: claim tx
5240                 assert_eq!(b_txn.len(), 1);
5241                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5242                 b_txn.clear();
5243         }
5244         check_added_monitors!(nodes[1], 1);
5245         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5246         assert_eq!(msg_events.len(), 3);
5247         match msg_events[0] {
5248                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5249                 _ => panic!("Unexpected event"),
5250         }
5251         match msg_events[1] {
5252                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5253                 _ => panic!("Unexpected event"),
5254         }
5255         match msg_events[2] {
5256                 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, .. } } => {
5257                         assert!(update_add_htlcs.is_empty());
5258                         assert!(update_fail_htlcs.is_empty());
5259                         assert_eq!(update_fulfill_htlcs.len(), 1);
5260                         assert!(update_fail_malformed_htlcs.is_empty());
5261                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5262                 },
5263                 _ => panic!("Unexpected event"),
5264         };
5265         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5266         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5267         mine_transaction(&nodes[1], &commitment_tx[0]);
5268         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5269         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5270         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5271         assert_eq!(b_txn.len(), 3);
5272         check_spends!(b_txn[1], chan_1.3);
5273         check_spends!(b_txn[2], b_txn[1]);
5274         check_spends!(b_txn[0], commitment_tx[0]);
5275         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5276         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5277         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5278
5279         check_closed_broadcast!(nodes[1], true);
5280         check_added_monitors!(nodes[1], 1);
5281 }
5282
5283 #[test]
5284 fn test_duplicate_payment_hash_one_failure_one_success() {
5285         // Topology : A --> B --> C --> D
5286         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5287         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5288         // we forward one of the payments onwards to D.
5289         let chanmon_cfgs = create_chanmon_cfgs(4);
5290         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5291         // When this test was written, the default base fee floated based on the HTLC count.
5292         // It is now fixed, so we simply set the fee to the expected value here.
5293         let mut config = test_default_channel_config();
5294         config.channel_config.forwarding_fee_base_msat = 196;
5295         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5296                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5297         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5298
5299         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5300         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5301         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5302
5303         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5304         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5305         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5306         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5307         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5308
5309         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5310
5311         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5312         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5313         // script push size limit so that the below script length checks match
5314         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5315         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5316                 .with_features(InvoiceFeatures::known());
5317         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5318         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5319
5320         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5321         assert_eq!(commitment_txn[0].input.len(), 1);
5322         check_spends!(commitment_txn[0], chan_2.3);
5323
5324         mine_transaction(&nodes[1], &commitment_txn[0]);
5325         check_closed_broadcast!(nodes[1], true);
5326         check_added_monitors!(nodes[1], 1);
5327         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5328         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5329
5330         let htlc_timeout_tx;
5331         { // Extract one of the two HTLC-Timeout transaction
5332                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5333                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5334                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5335                 check_spends!(node_txn[0], chan_2.3);
5336
5337                 check_spends!(node_txn[1], commitment_txn[0]);
5338                 assert_eq!(node_txn[1].input.len(), 1);
5339
5340                 if node_txn.len() > 3 {
5341                         check_spends!(node_txn[2], commitment_txn[0]);
5342                         assert_eq!(node_txn[2].input.len(), 1);
5343                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5344
5345                         check_spends!(node_txn[3], commitment_txn[0]);
5346                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5347                 } else {
5348                         check_spends!(node_txn[2], commitment_txn[0]);
5349                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5350                 }
5351
5352                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5353                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5354                 if node_txn.len() > 3 {
5355                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5356                 }
5357                 htlc_timeout_tx = node_txn[1].clone();
5358         }
5359
5360         nodes[2].node.claim_funds(our_payment_preimage);
5361         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5362
5363         mine_transaction(&nodes[2], &commitment_txn[0]);
5364         check_added_monitors!(nodes[2], 2);
5365         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5366         let events = nodes[2].node.get_and_clear_pending_msg_events();
5367         match events[0] {
5368                 MessageSendEvent::UpdateHTLCs { .. } => {},
5369                 _ => panic!("Unexpected event"),
5370         }
5371         match events[1] {
5372                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5373                 _ => panic!("Unexepected event"),
5374         }
5375         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5376         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)
5377         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5378         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5379         assert_eq!(htlc_success_txn[0].input.len(), 1);
5380         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5381         assert_eq!(htlc_success_txn[1].input.len(), 1);
5382         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5383         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5384         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5385         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5386         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5387         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5388
5389         mine_transaction(&nodes[1], &htlc_timeout_tx);
5390         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5391         expect_pending_htlcs_forwardable!(nodes[1]);
5392         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5393         assert!(htlc_updates.update_add_htlcs.is_empty());
5394         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5395         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5396         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5397         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5398         check_added_monitors!(nodes[1], 1);
5399
5400         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5401         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5402         {
5403                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5404         }
5405         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5406
5407         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5408         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5409         // and nodes[2] fee) is rounded down and then claimed in full.
5410         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5411         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5412         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5413         assert!(updates.update_add_htlcs.is_empty());
5414         assert!(updates.update_fail_htlcs.is_empty());
5415         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5416         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5417         assert!(updates.update_fail_malformed_htlcs.is_empty());
5418         check_added_monitors!(nodes[1], 1);
5419
5420         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5421         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5422
5423         let events = nodes[0].node.get_and_clear_pending_events();
5424         match events[0] {
5425                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5426                         assert_eq!(*payment_preimage, our_payment_preimage);
5427                         assert_eq!(*payment_hash, duplicate_payment_hash);
5428                 }
5429                 _ => panic!("Unexpected event"),
5430         }
5431 }
5432
5433 #[test]
5434 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5435         let chanmon_cfgs = create_chanmon_cfgs(2);
5436         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5437         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5438         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5439
5440         // Create some initial channels
5441         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5442
5443         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5444         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5445         assert_eq!(local_txn.len(), 1);
5446         assert_eq!(local_txn[0].input.len(), 1);
5447         check_spends!(local_txn[0], chan_1.3);
5448
5449         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5450         nodes[1].node.claim_funds(payment_preimage);
5451         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5452         check_added_monitors!(nodes[1], 1);
5453
5454         mine_transaction(&nodes[1], &local_txn[0]);
5455         check_added_monitors!(nodes[1], 1);
5456         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5457         let events = nodes[1].node.get_and_clear_pending_msg_events();
5458         match events[0] {
5459                 MessageSendEvent::UpdateHTLCs { .. } => {},
5460                 _ => panic!("Unexpected event"),
5461         }
5462         match events[1] {
5463                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5464                 _ => panic!("Unexepected event"),
5465         }
5466         let node_tx = {
5467                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5468                 assert_eq!(node_txn.len(), 3);
5469                 assert_eq!(node_txn[0], node_txn[2]);
5470                 assert_eq!(node_txn[1], local_txn[0]);
5471                 assert_eq!(node_txn[0].input.len(), 1);
5472                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5473                 check_spends!(node_txn[0], local_txn[0]);
5474                 node_txn[0].clone()
5475         };
5476
5477         mine_transaction(&nodes[1], &node_tx);
5478         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5479
5480         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5481         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5482         assert_eq!(spend_txn.len(), 1);
5483         assert_eq!(spend_txn[0].input.len(), 1);
5484         check_spends!(spend_txn[0], node_tx);
5485         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5486 }
5487
5488 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5489         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5490         // unrevoked commitment transaction.
5491         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5492         // a remote RAA before they could be failed backwards (and combinations thereof).
5493         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5494         // use the same payment hashes.
5495         // Thus, we use a six-node network:
5496         //
5497         // A \         / E
5498         //    - C - D -
5499         // B /         \ F
5500         // And test where C fails back to A/B when D announces its latest commitment transaction
5501         let chanmon_cfgs = create_chanmon_cfgs(6);
5502         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5503         // When this test was written, the default base fee floated based on the HTLC count.
5504         // It is now fixed, so we simply set the fee to the expected value here.
5505         let mut config = test_default_channel_config();
5506         config.channel_config.forwarding_fee_base_msat = 196;
5507         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5508                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5509         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5510
5511         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5512         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5513         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5514         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5515         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5516
5517         // Rebalance and check output sanity...
5518         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5519         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5520         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5521
5522         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5523         // 0th HTLC:
5524         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
5525         // 1st HTLC:
5526         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
5527         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5528         // 2nd HTLC:
5529         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
5530         // 3rd HTLC:
5531         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
5532         // 4th HTLC:
5533         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5534         // 5th HTLC:
5535         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5536         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5537         // 6th HTLC:
5538         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());
5539         // 7th HTLC:
5540         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());
5541
5542         // 8th HTLC:
5543         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5544         // 9th HTLC:
5545         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5546         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
5547
5548         // 10th HTLC:
5549         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
5550         // 11th HTLC:
5551         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5552         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());
5553
5554         // Double-check that six of the new HTLC were added
5555         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5556         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5557         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5558         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5559
5560         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5561         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5562         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5563         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5564         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5565         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5566         check_added_monitors!(nodes[4], 0);
5567         expect_pending_htlcs_forwardable!(nodes[4]);
5568         check_added_monitors!(nodes[4], 1);
5569
5570         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5571         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5572         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5573         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5574         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5575         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5576
5577         // Fail 3rd below-dust and 7th above-dust HTLCs
5578         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5579         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5580         check_added_monitors!(nodes[5], 0);
5581         expect_pending_htlcs_forwardable!(nodes[5]);
5582         check_added_monitors!(nodes[5], 1);
5583
5584         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5585         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5586         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5587         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5588
5589         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5590
5591         expect_pending_htlcs_forwardable!(nodes[3]);
5592         check_added_monitors!(nodes[3], 1);
5593         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5594         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5595         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5596         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5597         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5598         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5599         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5600         if deliver_last_raa {
5601                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5602         } else {
5603                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5604         }
5605
5606         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5607         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5608         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5609         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5610         //
5611         // We now broadcast the latest commitment transaction, which *should* result in failures for
5612         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5613         // the non-broadcast above-dust HTLCs.
5614         //
5615         // Alternatively, we may broadcast the previous commitment transaction, which should only
5616         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5617         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5618
5619         if announce_latest {
5620                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5621         } else {
5622                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5623         }
5624         let events = nodes[2].node.get_and_clear_pending_events();
5625         let close_event = if deliver_last_raa {
5626                 assert_eq!(events.len(), 2);
5627                 events[1].clone()
5628         } else {
5629                 assert_eq!(events.len(), 1);
5630                 events[0].clone()
5631         };
5632         match close_event {
5633                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5634                 _ => panic!("Unexpected event"),
5635         }
5636
5637         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5638         check_closed_broadcast!(nodes[2], true);
5639         if deliver_last_raa {
5640                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5641         } else {
5642                 expect_pending_htlcs_forwardable!(nodes[2]);
5643         }
5644         check_added_monitors!(nodes[2], 3);
5645
5646         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5647         assert_eq!(cs_msgs.len(), 2);
5648         let mut a_done = false;
5649         for msg in cs_msgs {
5650                 match msg {
5651                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5652                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5653                                 // should be failed-backwards here.
5654                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5655                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5656                                         for htlc in &updates.update_fail_htlcs {
5657                                                 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 });
5658                                         }
5659                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5660                                         assert!(!a_done);
5661                                         a_done = true;
5662                                         &nodes[0]
5663                                 } else {
5664                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5665                                         for htlc in &updates.update_fail_htlcs {
5666                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5667                                         }
5668                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5669                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5670                                         &nodes[1]
5671                                 };
5672                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5673                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5674                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5675                                 if announce_latest {
5676                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5677                                         if *node_id == nodes[0].node.get_our_node_id() {
5678                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5679                                         }
5680                                 }
5681                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5682                         },
5683                         _ => panic!("Unexpected event"),
5684                 }
5685         }
5686
5687         let as_events = nodes[0].node.get_and_clear_pending_events();
5688         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5689         let mut as_failds = HashSet::new();
5690         let mut as_updates = 0;
5691         for event in as_events.iter() {
5692                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5693                         assert!(as_failds.insert(*payment_hash));
5694                         if *payment_hash != payment_hash_2 {
5695                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5696                         } else {
5697                                 assert!(!rejected_by_dest);
5698                         }
5699                         if network_update.is_some() {
5700                                 as_updates += 1;
5701                         }
5702                 } else { panic!("Unexpected event"); }
5703         }
5704         assert!(as_failds.contains(&payment_hash_1));
5705         assert!(as_failds.contains(&payment_hash_2));
5706         if announce_latest {
5707                 assert!(as_failds.contains(&payment_hash_3));
5708                 assert!(as_failds.contains(&payment_hash_5));
5709         }
5710         assert!(as_failds.contains(&payment_hash_6));
5711
5712         let bs_events = nodes[1].node.get_and_clear_pending_events();
5713         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5714         let mut bs_failds = HashSet::new();
5715         let mut bs_updates = 0;
5716         for event in bs_events.iter() {
5717                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5718                         assert!(bs_failds.insert(*payment_hash));
5719                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5720                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5721                         } else {
5722                                 assert!(!rejected_by_dest);
5723                         }
5724                         if network_update.is_some() {
5725                                 bs_updates += 1;
5726                         }
5727                 } else { panic!("Unexpected event"); }
5728         }
5729         assert!(bs_failds.contains(&payment_hash_1));
5730         assert!(bs_failds.contains(&payment_hash_2));
5731         if announce_latest {
5732                 assert!(bs_failds.contains(&payment_hash_4));
5733         }
5734         assert!(bs_failds.contains(&payment_hash_5));
5735
5736         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5737         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5738         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5739         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5740         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5741         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5742 }
5743
5744 #[test]
5745 fn test_fail_backwards_latest_remote_announce_a() {
5746         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5747 }
5748
5749 #[test]
5750 fn test_fail_backwards_latest_remote_announce_b() {
5751         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5752 }
5753
5754 #[test]
5755 fn test_fail_backwards_previous_remote_announce() {
5756         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5757         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5758         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5759 }
5760
5761 #[test]
5762 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5763         let chanmon_cfgs = create_chanmon_cfgs(2);
5764         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5765         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5766         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5767
5768         // Create some initial channels
5769         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5770
5771         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5772         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5773         assert_eq!(local_txn[0].input.len(), 1);
5774         check_spends!(local_txn[0], chan_1.3);
5775
5776         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5777         mine_transaction(&nodes[0], &local_txn[0]);
5778         check_closed_broadcast!(nodes[0], true);
5779         check_added_monitors!(nodes[0], 1);
5780         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5781         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5782
5783         let htlc_timeout = {
5784                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5785                 assert_eq!(node_txn.len(), 2);
5786                 check_spends!(node_txn[0], chan_1.3);
5787                 assert_eq!(node_txn[1].input.len(), 1);
5788                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5789                 check_spends!(node_txn[1], local_txn[0]);
5790                 node_txn[1].clone()
5791         };
5792
5793         mine_transaction(&nodes[0], &htlc_timeout);
5794         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5795         expect_payment_failed!(nodes[0], our_payment_hash, true);
5796
5797         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5798         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5799         assert_eq!(spend_txn.len(), 3);
5800         check_spends!(spend_txn[0], local_txn[0]);
5801         assert_eq!(spend_txn[1].input.len(), 1);
5802         check_spends!(spend_txn[1], htlc_timeout);
5803         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5804         assert_eq!(spend_txn[2].input.len(), 2);
5805         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5806         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5807                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5808 }
5809
5810 #[test]
5811 fn test_key_derivation_params() {
5812         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5813         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5814         // let us re-derive the channel key set to then derive a delayed_payment_key.
5815
5816         let chanmon_cfgs = create_chanmon_cfgs(3);
5817
5818         // We manually create the node configuration to backup the seed.
5819         let seed = [42; 32];
5820         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5821         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);
5822         let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5823         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() };
5824         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5825         node_cfgs.remove(0);
5826         node_cfgs.insert(0, node);
5827
5828         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5829         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5830
5831         // Create some initial channels
5832         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5833         // for node 0
5834         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5835         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5836         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5837
5838         // Ensure all nodes are at the same height
5839         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5840         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5841         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5842         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5843
5844         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5845         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5846         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5847         assert_eq!(local_txn_1[0].input.len(), 1);
5848         check_spends!(local_txn_1[0], chan_1.3);
5849
5850         // We check funding pubkey are unique
5851         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]));
5852         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]));
5853         if from_0_funding_key_0 == from_1_funding_key_0
5854             || from_0_funding_key_0 == from_1_funding_key_1
5855             || from_0_funding_key_1 == from_1_funding_key_0
5856             || from_0_funding_key_1 == from_1_funding_key_1 {
5857                 panic!("Funding pubkeys aren't unique");
5858         }
5859
5860         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5861         mine_transaction(&nodes[0], &local_txn_1[0]);
5862         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5863         check_closed_broadcast!(nodes[0], true);
5864         check_added_monitors!(nodes[0], 1);
5865         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5866
5867         let htlc_timeout = {
5868                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5869                 assert_eq!(node_txn[1].input.len(), 1);
5870                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5871                 check_spends!(node_txn[1], local_txn_1[0]);
5872                 node_txn[1].clone()
5873         };
5874
5875         mine_transaction(&nodes[0], &htlc_timeout);
5876         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5877         expect_payment_failed!(nodes[0], our_payment_hash, true);
5878
5879         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5880         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5881         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5882         assert_eq!(spend_txn.len(), 3);
5883         check_spends!(spend_txn[0], local_txn_1[0]);
5884         assert_eq!(spend_txn[1].input.len(), 1);
5885         check_spends!(spend_txn[1], htlc_timeout);
5886         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5887         assert_eq!(spend_txn[2].input.len(), 2);
5888         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5889         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5890                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5891 }
5892
5893 #[test]
5894 fn test_static_output_closing_tx() {
5895         let chanmon_cfgs = create_chanmon_cfgs(2);
5896         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5897         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5898         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5899
5900         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5901
5902         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5903         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5904
5905         mine_transaction(&nodes[0], &closing_tx);
5906         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5907         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5908
5909         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5910         assert_eq!(spend_txn.len(), 1);
5911         check_spends!(spend_txn[0], closing_tx);
5912
5913         mine_transaction(&nodes[1], &closing_tx);
5914         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5915         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5916
5917         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5918         assert_eq!(spend_txn.len(), 1);
5919         check_spends!(spend_txn[0], closing_tx);
5920 }
5921
5922 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5923         let chanmon_cfgs = create_chanmon_cfgs(2);
5924         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5925         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5926         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5927         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5928
5929         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5930
5931         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5932         // present in B's local commitment transaction, but none of A's commitment transactions.
5933         nodes[1].node.claim_funds(payment_preimage);
5934         check_added_monitors!(nodes[1], 1);
5935         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5936
5937         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5938         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5939         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5940
5941         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5942         check_added_monitors!(nodes[0], 1);
5943         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5944         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5945         check_added_monitors!(nodes[1], 1);
5946
5947         let starting_block = nodes[1].best_block_info();
5948         let mut block = Block {
5949                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5950                 txdata: vec![],
5951         };
5952         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5953                 connect_block(&nodes[1], &block);
5954                 block.header.prev_blockhash = block.block_hash();
5955         }
5956         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5957         check_closed_broadcast!(nodes[1], true);
5958         check_added_monitors!(nodes[1], 1);
5959         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5960 }
5961
5962 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5963         let chanmon_cfgs = create_chanmon_cfgs(2);
5964         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5965         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5966         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5967         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5968
5969         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5970         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5971         check_added_monitors!(nodes[0], 1);
5972
5973         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5974
5975         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5976         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5977         // to "time out" the HTLC.
5978
5979         let starting_block = nodes[1].best_block_info();
5980         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5981
5982         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5983                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5984                 header.prev_blockhash = header.block_hash();
5985         }
5986         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5987         check_closed_broadcast!(nodes[0], true);
5988         check_added_monitors!(nodes[0], 1);
5989         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5990 }
5991
5992 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5993         let chanmon_cfgs = create_chanmon_cfgs(3);
5994         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5995         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5996         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5997         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5998
5999         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6000         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6001         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6002         // actually revoked.
6003         let htlc_value = if use_dust { 50000 } else { 3000000 };
6004         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6005         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6006         expect_pending_htlcs_forwardable!(nodes[1]);
6007         check_added_monitors!(nodes[1], 1);
6008
6009         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6010         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6011         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6012         check_added_monitors!(nodes[0], 1);
6013         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6014         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6015         check_added_monitors!(nodes[1], 1);
6016         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6017         check_added_monitors!(nodes[1], 1);
6018         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6019
6020         if check_revoke_no_close {
6021                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6022                 check_added_monitors!(nodes[0], 1);
6023         }
6024
6025         let starting_block = nodes[1].best_block_info();
6026         let mut block = Block {
6027                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6028                 txdata: vec![],
6029         };
6030         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6031                 connect_block(&nodes[0], &block);
6032                 block.header.prev_blockhash = block.block_hash();
6033         }
6034         if !check_revoke_no_close {
6035                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6036                 check_closed_broadcast!(nodes[0], true);
6037                 check_added_monitors!(nodes[0], 1);
6038                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6039         } else {
6040                 let events = nodes[0].node.get_and_clear_pending_events();
6041                 assert_eq!(events.len(), 2);
6042                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6043                         assert_eq!(*payment_hash, our_payment_hash);
6044                 } else { panic!("Unexpected event"); }
6045                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6046                         assert_eq!(*payment_hash, our_payment_hash);
6047                 } else { panic!("Unexpected event"); }
6048         }
6049 }
6050
6051 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6052 // There are only a few cases to test here:
6053 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
6054 //    broadcastable commitment transactions result in channel closure,
6055 //  * its included in an unrevoked-but-previous remote commitment transaction,
6056 //  * its included in the latest remote or local commitment transactions.
6057 // We test each of the three possible commitment transactions individually and use both dust and
6058 // non-dust HTLCs.
6059 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6060 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6061 // tested for at least one of the cases in other tests.
6062 #[test]
6063 fn htlc_claim_single_commitment_only_a() {
6064         do_htlc_claim_local_commitment_only(true);
6065         do_htlc_claim_local_commitment_only(false);
6066
6067         do_htlc_claim_current_remote_commitment_only(true);
6068         do_htlc_claim_current_remote_commitment_only(false);
6069 }
6070
6071 #[test]
6072 fn htlc_claim_single_commitment_only_b() {
6073         do_htlc_claim_previous_remote_commitment_only(true, false);
6074         do_htlc_claim_previous_remote_commitment_only(false, false);
6075         do_htlc_claim_previous_remote_commitment_only(true, true);
6076         do_htlc_claim_previous_remote_commitment_only(false, true);
6077 }
6078
6079 #[test]
6080 #[should_panic]
6081 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6082         let chanmon_cfgs = create_chanmon_cfgs(2);
6083         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6084         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6085         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6086         // Force duplicate randomness for every get-random call
6087         for node in nodes.iter() {
6088                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6089         }
6090
6091         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6092         let channel_value_satoshis=10000;
6093         let push_msat=10001;
6094         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6095         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6096         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6097         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6098
6099         // Create a second channel with the same random values. This used to panic due to a colliding
6100         // channel_id, but now panics due to a colliding outbound SCID alias.
6101         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6102 }
6103
6104 #[test]
6105 fn bolt2_open_channel_sending_node_checks_part2() {
6106         let chanmon_cfgs = create_chanmon_cfgs(2);
6107         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6108         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6109         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6110
6111         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6112         let channel_value_satoshis=2^24;
6113         let push_msat=10001;
6114         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6115
6116         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6117         let channel_value_satoshis=10000;
6118         // Test when push_msat is equal to 1000 * funding_satoshis.
6119         let push_msat=1000*channel_value_satoshis+1;
6120         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6121
6122         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6123         let channel_value_satoshis=10000;
6124         let push_msat=10001;
6125         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
6126         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6127         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6128
6129         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6130         // 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
6131         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6132
6133         // 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.
6134         assert!(BREAKDOWN_TIMEOUT>0);
6135         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6136
6137         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6138         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6139         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6140
6141         // 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.
6142         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6143         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6144         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6145         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6146         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6147 }
6148
6149 #[test]
6150 fn bolt2_open_channel_sane_dust_limit() {
6151         let chanmon_cfgs = create_chanmon_cfgs(2);
6152         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6153         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6154         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6155
6156         let channel_value_satoshis=1000000;
6157         let push_msat=10001;
6158         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6159         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6160         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6161         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6162
6163         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6164         let events = nodes[1].node.get_and_clear_pending_msg_events();
6165         let err_msg = match events[0] {
6166                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6167                         msg.clone()
6168                 },
6169                 _ => panic!("Unexpected event"),
6170         };
6171         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6172 }
6173
6174 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6175 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6176 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6177 // is no longer affordable once it's freed.
6178 #[test]
6179 fn test_fail_holding_cell_htlc_upon_free() {
6180         let chanmon_cfgs = create_chanmon_cfgs(2);
6181         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6182         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6183         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6184         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6185
6186         // First nodes[0] generates an update_fee, setting the channel's
6187         // pending_update_fee.
6188         {
6189                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6190                 *feerate_lock += 20;
6191         }
6192         nodes[0].node.timer_tick_occurred();
6193         check_added_monitors!(nodes[0], 1);
6194
6195         let events = nodes[0].node.get_and_clear_pending_msg_events();
6196         assert_eq!(events.len(), 1);
6197         let (update_msg, commitment_signed) = match events[0] {
6198                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6199                         (update_fee.as_ref(), commitment_signed)
6200                 },
6201                 _ => panic!("Unexpected event"),
6202         };
6203
6204         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6205
6206         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6207         let channel_reserve = chan_stat.channel_reserve_msat;
6208         let feerate = get_feerate!(nodes[0], chan.2);
6209         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6210
6211         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6212         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6213         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6214
6215         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6216         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6217         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6218         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6219
6220         // Flush the pending fee update.
6221         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6222         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6223         check_added_monitors!(nodes[1], 1);
6224         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6225         check_added_monitors!(nodes[0], 1);
6226
6227         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6228         // HTLC, but now that the fee has been raised the payment will now fail, causing
6229         // us to surface its failure to the user.
6230         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6231         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6232         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);
6233         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 {}",
6234                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6235         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6236
6237         // Check that the payment failed to be sent out.
6238         let events = nodes[0].node.get_and_clear_pending_events();
6239         assert_eq!(events.len(), 1);
6240         match &events[0] {
6241                 &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, .. } => {
6242                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6243                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6244                         assert_eq!(*rejected_by_dest, false);
6245                         assert_eq!(*all_paths_failed, true);
6246                         assert_eq!(*network_update, None);
6247                         assert_eq!(*short_channel_id, None);
6248                         assert_eq!(*error_code, None);
6249                         assert_eq!(*error_data, None);
6250                 },
6251                 _ => panic!("Unexpected event"),
6252         }
6253 }
6254
6255 // Test that if multiple HTLCs are released from the holding cell and one is
6256 // valid but the other is no longer valid upon release, the valid HTLC can be
6257 // successfully completed while the other one fails as expected.
6258 #[test]
6259 fn test_free_and_fail_holding_cell_htlcs() {
6260         let chanmon_cfgs = create_chanmon_cfgs(2);
6261         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6262         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6263         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6264         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6265
6266         // First nodes[0] generates an update_fee, setting the channel's
6267         // pending_update_fee.
6268         {
6269                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6270                 *feerate_lock += 200;
6271         }
6272         nodes[0].node.timer_tick_occurred();
6273         check_added_monitors!(nodes[0], 1);
6274
6275         let events = nodes[0].node.get_and_clear_pending_msg_events();
6276         assert_eq!(events.len(), 1);
6277         let (update_msg, commitment_signed) = match events[0] {
6278                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6279                         (update_fee.as_ref(), commitment_signed)
6280                 },
6281                 _ => panic!("Unexpected event"),
6282         };
6283
6284         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6285
6286         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6287         let channel_reserve = chan_stat.channel_reserve_msat;
6288         let feerate = get_feerate!(nodes[0], chan.2);
6289         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6290
6291         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6292         let amt_1 = 20000;
6293         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6294         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6295         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6296
6297         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6298         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6299         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6300         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6301         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6302         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6303         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6304
6305         // Flush the pending fee update.
6306         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6307         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6308         check_added_monitors!(nodes[1], 1);
6309         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6310         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6311         check_added_monitors!(nodes[0], 2);
6312
6313         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6314         // but now that the fee has been raised the second payment will now fail, causing us
6315         // to surface its failure to the user. The first payment should succeed.
6316         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6317         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6318         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);
6319         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 {}",
6320                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6321         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6322
6323         // Check that the second payment failed to be sent out.
6324         let events = nodes[0].node.get_and_clear_pending_events();
6325         assert_eq!(events.len(), 1);
6326         match &events[0] {
6327                 &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, .. } => {
6328                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6329                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6330                         assert_eq!(*rejected_by_dest, false);
6331                         assert_eq!(*all_paths_failed, true);
6332                         assert_eq!(*network_update, None);
6333                         assert_eq!(*short_channel_id, None);
6334                         assert_eq!(*error_code, None);
6335                         assert_eq!(*error_data, None);
6336                 },
6337                 _ => panic!("Unexpected event"),
6338         }
6339
6340         // Complete the first payment and the RAA from the fee update.
6341         let (payment_event, send_raa_event) = {
6342                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6343                 assert_eq!(msgs.len(), 2);
6344                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6345         };
6346         let raa = match send_raa_event {
6347                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6348                 _ => panic!("Unexpected event"),
6349         };
6350         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6351         check_added_monitors!(nodes[1], 1);
6352         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6353         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6354         let events = nodes[1].node.get_and_clear_pending_events();
6355         assert_eq!(events.len(), 1);
6356         match events[0] {
6357                 Event::PendingHTLCsForwardable { .. } => {},
6358                 _ => panic!("Unexpected event"),
6359         }
6360         nodes[1].node.process_pending_htlc_forwards();
6361         let events = nodes[1].node.get_and_clear_pending_events();
6362         assert_eq!(events.len(), 1);
6363         match events[0] {
6364                 Event::PaymentReceived { .. } => {},
6365                 _ => panic!("Unexpected event"),
6366         }
6367         nodes[1].node.claim_funds(payment_preimage_1);
6368         check_added_monitors!(nodes[1], 1);
6369         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6370
6371         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6372         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6373         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6374         expect_payment_sent!(nodes[0], payment_preimage_1);
6375 }
6376
6377 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6378 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6379 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6380 // once it's freed.
6381 #[test]
6382 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6383         let chanmon_cfgs = create_chanmon_cfgs(3);
6384         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6385         // When this test was written, the default base fee floated based on the HTLC count.
6386         // It is now fixed, so we simply set the fee to the expected value here.
6387         let mut config = test_default_channel_config();
6388         config.channel_config.forwarding_fee_base_msat = 196;
6389         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6390         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6391         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6392         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6393
6394         // First nodes[1] generates an update_fee, setting the channel's
6395         // pending_update_fee.
6396         {
6397                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6398                 *feerate_lock += 20;
6399         }
6400         nodes[1].node.timer_tick_occurred();
6401         check_added_monitors!(nodes[1], 1);
6402
6403         let events = nodes[1].node.get_and_clear_pending_msg_events();
6404         assert_eq!(events.len(), 1);
6405         let (update_msg, commitment_signed) = match events[0] {
6406                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6407                         (update_fee.as_ref(), commitment_signed)
6408                 },
6409                 _ => panic!("Unexpected event"),
6410         };
6411
6412         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6413
6414         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6415         let channel_reserve = chan_stat.channel_reserve_msat;
6416         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6417         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6418
6419         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6420         let feemsat = 239;
6421         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6422         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6423         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6424         let payment_event = {
6425                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6426                 check_added_monitors!(nodes[0], 1);
6427
6428                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6429                 assert_eq!(events.len(), 1);
6430
6431                 SendEvent::from_event(events.remove(0))
6432         };
6433         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6434         check_added_monitors!(nodes[1], 0);
6435         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6436         expect_pending_htlcs_forwardable!(nodes[1]);
6437
6438         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6439         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6440
6441         // Flush the pending fee update.
6442         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6443         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6444         check_added_monitors!(nodes[2], 1);
6445         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6446         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6447         check_added_monitors!(nodes[1], 2);
6448
6449         // A final RAA message is generated to finalize the fee update.
6450         let events = nodes[1].node.get_and_clear_pending_msg_events();
6451         assert_eq!(events.len(), 1);
6452
6453         let raa_msg = match &events[0] {
6454                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6455                         msg.clone()
6456                 },
6457                 _ => panic!("Unexpected event"),
6458         };
6459
6460         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6461         check_added_monitors!(nodes[2], 1);
6462         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6463
6464         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6465         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6466         assert_eq!(process_htlc_forwards_event.len(), 1);
6467         match &process_htlc_forwards_event[0] {
6468                 &Event::PendingHTLCsForwardable { .. } => {},
6469                 _ => panic!("Unexpected event"),
6470         }
6471
6472         // In response, we call ChannelManager's process_pending_htlc_forwards
6473         nodes[1].node.process_pending_htlc_forwards();
6474         check_added_monitors!(nodes[1], 1);
6475
6476         // This causes the HTLC to be failed backwards.
6477         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6478         assert_eq!(fail_event.len(), 1);
6479         let (fail_msg, commitment_signed) = match &fail_event[0] {
6480                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6481                         assert_eq!(updates.update_add_htlcs.len(), 0);
6482                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6483                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6484                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6485                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6486                 },
6487                 _ => panic!("Unexpected event"),
6488         };
6489
6490         // Pass the failure messages back to nodes[0].
6491         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6492         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6493
6494         // Complete the HTLC failure+removal process.
6495         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6496         check_added_monitors!(nodes[0], 1);
6497         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6498         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6499         check_added_monitors!(nodes[1], 2);
6500         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6501         assert_eq!(final_raa_event.len(), 1);
6502         let raa = match &final_raa_event[0] {
6503                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6504                 _ => panic!("Unexpected event"),
6505         };
6506         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6507         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6508         check_added_monitors!(nodes[0], 1);
6509 }
6510
6511 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6512 // 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.
6513 //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.
6514
6515 #[test]
6516 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6517         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6518         let chanmon_cfgs = create_chanmon_cfgs(2);
6519         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6520         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6521         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6522         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6523
6524         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6525         route.paths[0][0].fee_msat = 100;
6526
6527         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6528                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6529         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6530         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6531 }
6532
6533 #[test]
6534 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6535         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6536         let chanmon_cfgs = create_chanmon_cfgs(2);
6537         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6538         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6539         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6540         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6541
6542         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6543         route.paths[0][0].fee_msat = 0;
6544         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6545                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6546
6547         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6548         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6549 }
6550
6551 #[test]
6552 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6553         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6554         let chanmon_cfgs = create_chanmon_cfgs(2);
6555         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6556         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6557         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6558         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6559
6560         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6561         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6562         check_added_monitors!(nodes[0], 1);
6563         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6564         updates.update_add_htlcs[0].amount_msat = 0;
6565
6566         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6567         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6568         check_closed_broadcast!(nodes[1], true).unwrap();
6569         check_added_monitors!(nodes[1], 1);
6570         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6571 }
6572
6573 #[test]
6574 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6575         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6576         //It is enforced when constructing a route.
6577         let chanmon_cfgs = create_chanmon_cfgs(2);
6578         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6579         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6580         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6581         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6582
6583         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6584                 .with_features(InvoiceFeatures::known());
6585         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6586         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6587         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6588                 assert_eq!(err, &"Channel CLTV overflowed?"));
6589 }
6590
6591 #[test]
6592 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6593         //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.
6594         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6595         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6596         let chanmon_cfgs = create_chanmon_cfgs(2);
6597         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6598         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6599         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6600         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6601         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6602
6603         for i in 0..max_accepted_htlcs {
6604                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6605                 let payment_event = {
6606                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6607                         check_added_monitors!(nodes[0], 1);
6608
6609                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6610                         assert_eq!(events.len(), 1);
6611                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6612                                 assert_eq!(htlcs[0].htlc_id, i);
6613                         } else {
6614                                 assert!(false);
6615                         }
6616                         SendEvent::from_event(events.remove(0))
6617                 };
6618                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6619                 check_added_monitors!(nodes[1], 0);
6620                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6621
6622                 expect_pending_htlcs_forwardable!(nodes[1]);
6623                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6624         }
6625         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6626         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6627                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6628
6629         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6630         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6631 }
6632
6633 #[test]
6634 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6635         //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.
6636         let chanmon_cfgs = create_chanmon_cfgs(2);
6637         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6638         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6639         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6640         let channel_value = 100000;
6641         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6642         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6643
6644         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6645
6646         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6647         // Manually create a route over our max in flight (which our router normally automatically
6648         // limits us to.
6649         route.paths[0][0].fee_msat =  max_in_flight + 1;
6650         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6651                 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)));
6652
6653         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6654         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);
6655
6656         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6657 }
6658
6659 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6660 #[test]
6661 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6662         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6663         let chanmon_cfgs = create_chanmon_cfgs(2);
6664         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6665         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6666         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6667         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6668         let htlc_minimum_msat: u64;
6669         {
6670                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6671                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6672                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6673         }
6674
6675         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6676         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6677         check_added_monitors!(nodes[0], 1);
6678         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6679         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6680         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6681         assert!(nodes[1].node.list_channels().is_empty());
6682         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6683         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()));
6684         check_added_monitors!(nodes[1], 1);
6685         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6686 }
6687
6688 #[test]
6689 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6690         //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
6691         let chanmon_cfgs = create_chanmon_cfgs(2);
6692         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6693         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6694         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6695         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6696
6697         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6698         let channel_reserve = chan_stat.channel_reserve_msat;
6699         let feerate = get_feerate!(nodes[0], chan.2);
6700         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6701         // The 2* and +1 are for the fee spike reserve.
6702         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6703
6704         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6705         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6706         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6707         check_added_monitors!(nodes[0], 1);
6708         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6709
6710         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6711         // at this time channel-initiatee receivers are not required to enforce that senders
6712         // respect the fee_spike_reserve.
6713         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6714         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6715
6716         assert!(nodes[1].node.list_channels().is_empty());
6717         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6718         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6719         check_added_monitors!(nodes[1], 1);
6720         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6721 }
6722
6723 #[test]
6724 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6725         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6726         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6727         let chanmon_cfgs = create_chanmon_cfgs(2);
6728         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6729         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6730         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6731         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6732
6733         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6734         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6735         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6736         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6737         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6738         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6739
6740         let mut msg = msgs::UpdateAddHTLC {
6741                 channel_id: chan.2,
6742                 htlc_id: 0,
6743                 amount_msat: 1000,
6744                 payment_hash: our_payment_hash,
6745                 cltv_expiry: htlc_cltv,
6746                 onion_routing_packet: onion_packet.clone(),
6747         };
6748
6749         for i in 0..super::channel::OUR_MAX_HTLCS {
6750                 msg.htlc_id = i as u64;
6751                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6752         }
6753         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6754         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6755
6756         assert!(nodes[1].node.list_channels().is_empty());
6757         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6758         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6759         check_added_monitors!(nodes[1], 1);
6760         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6761 }
6762
6763 #[test]
6764 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6765         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6766         let chanmon_cfgs = create_chanmon_cfgs(2);
6767         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6768         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6769         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6770         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6771
6772         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6773         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6774         check_added_monitors!(nodes[0], 1);
6775         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6776         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6777         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6778
6779         assert!(nodes[1].node.list_channels().is_empty());
6780         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6781         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6782         check_added_monitors!(nodes[1], 1);
6783         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6784 }
6785
6786 #[test]
6787 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6788         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6789         let chanmon_cfgs = create_chanmon_cfgs(2);
6790         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6791         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6792         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6793
6794         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6795         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6796         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6797         check_added_monitors!(nodes[0], 1);
6798         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6799         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6800         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6801
6802         assert!(nodes[1].node.list_channels().is_empty());
6803         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6804         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6805         check_added_monitors!(nodes[1], 1);
6806         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6807 }
6808
6809 #[test]
6810 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6811         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6812         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6813         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6814         let chanmon_cfgs = create_chanmon_cfgs(2);
6815         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6816         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6817         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6818
6819         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6820         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6821         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6822         check_added_monitors!(nodes[0], 1);
6823         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6824         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6825
6826         //Disconnect and Reconnect
6827         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6828         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6829         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6830         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6831         assert_eq!(reestablish_1.len(), 1);
6832         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6833         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6834         assert_eq!(reestablish_2.len(), 1);
6835         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6836         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6837         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6838         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6839
6840         //Resend HTLC
6841         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6842         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6843         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6844         check_added_monitors!(nodes[1], 1);
6845         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6846
6847         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6848
6849         assert!(nodes[1].node.list_channels().is_empty());
6850         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6851         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6852         check_added_monitors!(nodes[1], 1);
6853         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6854 }
6855
6856 #[test]
6857 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6858         //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.
6859
6860         let chanmon_cfgs = create_chanmon_cfgs(2);
6861         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6862         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6863         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6864         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6865         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6866         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6867
6868         check_added_monitors!(nodes[0], 1);
6869         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6870         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6871
6872         let update_msg = msgs::UpdateFulfillHTLC{
6873                 channel_id: chan.2,
6874                 htlc_id: 0,
6875                 payment_preimage: our_payment_preimage,
6876         };
6877
6878         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6879
6880         assert!(nodes[0].node.list_channels().is_empty());
6881         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6882         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()));
6883         check_added_monitors!(nodes[0], 1);
6884         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6885 }
6886
6887 #[test]
6888 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6889         //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.
6890
6891         let chanmon_cfgs = create_chanmon_cfgs(2);
6892         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6893         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6894         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6895         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6896
6897         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6898         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6899         check_added_monitors!(nodes[0], 1);
6900         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6901         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6902
6903         let update_msg = msgs::UpdateFailHTLC{
6904                 channel_id: chan.2,
6905                 htlc_id: 0,
6906                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6907         };
6908
6909         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6910
6911         assert!(nodes[0].node.list_channels().is_empty());
6912         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6913         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()));
6914         check_added_monitors!(nodes[0], 1);
6915         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6916 }
6917
6918 #[test]
6919 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6920         //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.
6921
6922         let chanmon_cfgs = create_chanmon_cfgs(2);
6923         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6924         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6925         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6926         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6927
6928         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6929         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6930         check_added_monitors!(nodes[0], 1);
6931         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6932         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6933         let update_msg = msgs::UpdateFailMalformedHTLC{
6934                 channel_id: chan.2,
6935                 htlc_id: 0,
6936                 sha256_of_onion: [1; 32],
6937                 failure_code: 0x8000,
6938         };
6939
6940         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6941
6942         assert!(nodes[0].node.list_channels().is_empty());
6943         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6944         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()));
6945         check_added_monitors!(nodes[0], 1);
6946         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6947 }
6948
6949 #[test]
6950 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6951         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6952
6953         let chanmon_cfgs = create_chanmon_cfgs(2);
6954         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6955         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6956         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6957         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6958
6959         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6960
6961         nodes[1].node.claim_funds(our_payment_preimage);
6962         check_added_monitors!(nodes[1], 1);
6963         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6964
6965         let events = nodes[1].node.get_and_clear_pending_msg_events();
6966         assert_eq!(events.len(), 1);
6967         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6968                 match events[0] {
6969                         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, .. } } => {
6970                                 assert!(update_add_htlcs.is_empty());
6971                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6972                                 assert!(update_fail_htlcs.is_empty());
6973                                 assert!(update_fail_malformed_htlcs.is_empty());
6974                                 assert!(update_fee.is_none());
6975                                 update_fulfill_htlcs[0].clone()
6976                         },
6977                         _ => panic!("Unexpected event"),
6978                 }
6979         };
6980
6981         update_fulfill_msg.htlc_id = 1;
6982
6983         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6984
6985         assert!(nodes[0].node.list_channels().is_empty());
6986         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6987         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6988         check_added_monitors!(nodes[0], 1);
6989         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6990 }
6991
6992 #[test]
6993 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6994         //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.
6995
6996         let chanmon_cfgs = create_chanmon_cfgs(2);
6997         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6998         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6999         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7000         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7001
7002         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
7003
7004         nodes[1].node.claim_funds(our_payment_preimage);
7005         check_added_monitors!(nodes[1], 1);
7006         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7007
7008         let events = nodes[1].node.get_and_clear_pending_msg_events();
7009         assert_eq!(events.len(), 1);
7010         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7011                 match events[0] {
7012                         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, .. } } => {
7013                                 assert!(update_add_htlcs.is_empty());
7014                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7015                                 assert!(update_fail_htlcs.is_empty());
7016                                 assert!(update_fail_malformed_htlcs.is_empty());
7017                                 assert!(update_fee.is_none());
7018                                 update_fulfill_htlcs[0].clone()
7019                         },
7020                         _ => panic!("Unexpected event"),
7021                 }
7022         };
7023
7024         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7025
7026         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7027
7028         assert!(nodes[0].node.list_channels().is_empty());
7029         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7030         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7031         check_added_monitors!(nodes[0], 1);
7032         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7033 }
7034
7035 #[test]
7036 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7037         //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.
7038
7039         let chanmon_cfgs = create_chanmon_cfgs(2);
7040         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7041         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7042         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7043         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7044
7045         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7046         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7047         check_added_monitors!(nodes[0], 1);
7048
7049         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7050         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7051
7052         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7053         check_added_monitors!(nodes[1], 0);
7054         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7055
7056         let events = nodes[1].node.get_and_clear_pending_msg_events();
7057
7058         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7059                 match events[0] {
7060                         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, .. } } => {
7061                                 assert!(update_add_htlcs.is_empty());
7062                                 assert!(update_fulfill_htlcs.is_empty());
7063                                 assert!(update_fail_htlcs.is_empty());
7064                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7065                                 assert!(update_fee.is_none());
7066                                 update_fail_malformed_htlcs[0].clone()
7067                         },
7068                         _ => panic!("Unexpected event"),
7069                 }
7070         };
7071         update_msg.failure_code &= !0x8000;
7072         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7073
7074         assert!(nodes[0].node.list_channels().is_empty());
7075         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7076         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7077         check_added_monitors!(nodes[0], 1);
7078         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7079 }
7080
7081 #[test]
7082 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7083         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7084         //    * 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.
7085
7086         let chanmon_cfgs = create_chanmon_cfgs(3);
7087         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7088         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7089         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7090         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7091         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7092
7093         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7094
7095         //First hop
7096         let mut payment_event = {
7097                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7098                 check_added_monitors!(nodes[0], 1);
7099                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7100                 assert_eq!(events.len(), 1);
7101                 SendEvent::from_event(events.remove(0))
7102         };
7103         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7104         check_added_monitors!(nodes[1], 0);
7105         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7106         expect_pending_htlcs_forwardable!(nodes[1]);
7107         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7108         assert_eq!(events_2.len(), 1);
7109         check_added_monitors!(nodes[1], 1);
7110         payment_event = SendEvent::from_event(events_2.remove(0));
7111         assert_eq!(payment_event.msgs.len(), 1);
7112
7113         //Second Hop
7114         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7115         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7116         check_added_monitors!(nodes[2], 0);
7117         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7118
7119         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7120         assert_eq!(events_3.len(), 1);
7121         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7122                 match events_3[0] {
7123                         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 } } => {
7124                                 assert!(update_add_htlcs.is_empty());
7125                                 assert!(update_fulfill_htlcs.is_empty());
7126                                 assert!(update_fail_htlcs.is_empty());
7127                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7128                                 assert!(update_fee.is_none());
7129                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7130                         },
7131                         _ => panic!("Unexpected event"),
7132                 }
7133         };
7134
7135         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7136
7137         check_added_monitors!(nodes[1], 0);
7138         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7139         expect_pending_htlcs_forwardable!(nodes[1]);
7140         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7141         assert_eq!(events_4.len(), 1);
7142
7143         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7144         match events_4[0] {
7145                 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, .. } } => {
7146                         assert!(update_add_htlcs.is_empty());
7147                         assert!(update_fulfill_htlcs.is_empty());
7148                         assert_eq!(update_fail_htlcs.len(), 1);
7149                         assert!(update_fail_malformed_htlcs.is_empty());
7150                         assert!(update_fee.is_none());
7151                 },
7152                 _ => panic!("Unexpected event"),
7153         };
7154
7155         check_added_monitors!(nodes[1], 1);
7156 }
7157
7158 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7159         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7160         // 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
7161         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7162
7163         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7164         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7165         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7166         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7167         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7168         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7169
7170         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7171
7172         // We route 2 dust-HTLCs between A and B
7173         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7174         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7175         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7176
7177         // Cache one local commitment tx as previous
7178         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7179
7180         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7181         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7182         check_added_monitors!(nodes[1], 0);
7183         expect_pending_htlcs_forwardable!(nodes[1]);
7184         check_added_monitors!(nodes[1], 1);
7185
7186         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7187         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7188         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7189         check_added_monitors!(nodes[0], 1);
7190
7191         // Cache one local commitment tx as lastest
7192         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7193
7194         let events = nodes[0].node.get_and_clear_pending_msg_events();
7195         match events[0] {
7196                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7197                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7198                 },
7199                 _ => panic!("Unexpected event"),
7200         }
7201         match events[1] {
7202                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7203                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7204                 },
7205                 _ => panic!("Unexpected event"),
7206         }
7207
7208         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7209         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7210         if announce_latest {
7211                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7212         } else {
7213                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7214         }
7215
7216         check_closed_broadcast!(nodes[0], true);
7217         check_added_monitors!(nodes[0], 1);
7218         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7219
7220         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7221         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7222         let events = nodes[0].node.get_and_clear_pending_events();
7223         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7224         assert_eq!(events.len(), 2);
7225         let mut first_failed = false;
7226         for event in events {
7227                 match event {
7228                         Event::PaymentPathFailed { payment_hash, .. } => {
7229                                 if payment_hash == payment_hash_1 {
7230                                         assert!(!first_failed);
7231                                         first_failed = true;
7232                                 } else {
7233                                         assert_eq!(payment_hash, payment_hash_2);
7234                                 }
7235                         }
7236                         _ => panic!("Unexpected event"),
7237                 }
7238         }
7239 }
7240
7241 #[test]
7242 fn test_failure_delay_dust_htlc_local_commitment() {
7243         do_test_failure_delay_dust_htlc_local_commitment(true);
7244         do_test_failure_delay_dust_htlc_local_commitment(false);
7245 }
7246
7247 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7248         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7249         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7250         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7251         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7252         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7253         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7254
7255         let chanmon_cfgs = create_chanmon_cfgs(3);
7256         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7257         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7258         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7259         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7260
7261         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7262
7263         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7264         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7265
7266         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7267         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7268
7269         // We revoked bs_commitment_tx
7270         if revoked {
7271                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7272                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7273         }
7274
7275         let mut timeout_tx = Vec::new();
7276         if local {
7277                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7278                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7279                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7280                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7281                 expect_payment_failed!(nodes[0], dust_hash, true);
7282
7283                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7284                 check_closed_broadcast!(nodes[0], true);
7285                 check_added_monitors!(nodes[0], 1);
7286                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7287                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7288                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7289                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7290                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7291                 mine_transaction(&nodes[0], &timeout_tx[0]);
7292                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7293                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7294         } else {
7295                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7296                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7297                 check_closed_broadcast!(nodes[0], true);
7298                 check_added_monitors!(nodes[0], 1);
7299                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7300                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7301
7302                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7303                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7304                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7305                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7306                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7307                 // dust HTLC should have been failed.
7308                 expect_payment_failed!(nodes[0], dust_hash, true);
7309
7310                 if !revoked {
7311                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7312                 } else {
7313                         assert_eq!(timeout_tx[0].lock_time, 0);
7314                 }
7315                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7316                 mine_transaction(&nodes[0], &timeout_tx[0]);
7317                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7318                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7319                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7320         }
7321 }
7322
7323 #[test]
7324 fn test_sweep_outbound_htlc_failure_update() {
7325         do_test_sweep_outbound_htlc_failure_update(false, true);
7326         do_test_sweep_outbound_htlc_failure_update(false, false);
7327         do_test_sweep_outbound_htlc_failure_update(true, false);
7328 }
7329
7330 #[test]
7331 fn test_user_configurable_csv_delay() {
7332         // We test our channel constructors yield errors when we pass them absurd csv delay
7333
7334         let mut low_our_to_self_config = UserConfig::default();
7335         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7336         let mut high_their_to_self_config = UserConfig::default();
7337         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7338         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7339         let chanmon_cfgs = create_chanmon_cfgs(2);
7340         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7341         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7342         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7343
7344         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7345         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7346                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7347                 &low_our_to_self_config, 0, 42)
7348         {
7349                 match error {
7350                         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())); },
7351                         _ => panic!("Unexpected event"),
7352                 }
7353         } else { assert!(false) }
7354
7355         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7356         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7357         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7358         open_channel.to_self_delay = 200;
7359         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7360                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7361                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7362         {
7363                 match error {
7364                         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()));  },
7365                         _ => panic!("Unexpected event"),
7366                 }
7367         } else { assert!(false); }
7368
7369         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7370         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7371         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()));
7372         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7373         accept_channel.to_self_delay = 200;
7374         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7375         let reason_msg;
7376         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7377                 match action {
7378                         &ErrorAction::SendErrorMessage { ref msg } => {
7379                                 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()));
7380                                 reason_msg = msg.data.clone();
7381                         },
7382                         _ => { panic!(); }
7383                 }
7384         } else { panic!(); }
7385         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7386
7387         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7388         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7389         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7390         open_channel.to_self_delay = 200;
7391         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7392                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7393                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7394         {
7395                 match error {
7396                         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())); },
7397                         _ => panic!("Unexpected event"),
7398                 }
7399         } else { assert!(false); }
7400 }
7401
7402 #[test]
7403 fn test_data_loss_protect() {
7404         // We want to be sure that :
7405         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7406         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7407         // * we close channel in case of detecting other being fallen behind
7408         // * we are able to claim our own outputs thanks to to_remote being static
7409         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7410         let persister;
7411         let logger;
7412         let fee_estimator;
7413         let tx_broadcaster;
7414         let chain_source;
7415         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7416         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7417         // during signing due to revoked tx
7418         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7419         let keys_manager = &chanmon_cfgs[0].keys_manager;
7420         let monitor;
7421         let node_state_0;
7422         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7423         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7424         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7425
7426         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7427
7428         // Cache node A state before any channel update
7429         let previous_node_state = nodes[0].node.encode();
7430         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7431         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7432
7433         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7434         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7435
7436         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7437         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7438
7439         // Restore node A from previous state
7440         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7441         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7442         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7443         tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7444         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7445         persister = test_utils::TestPersister::new();
7446         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7447         node_state_0 = {
7448                 let mut channel_monitors = HashMap::new();
7449                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7450                 <(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 {
7451                         keys_manager: keys_manager,
7452                         fee_estimator: &fee_estimator,
7453                         chain_monitor: &monitor,
7454                         logger: &logger,
7455                         tx_broadcaster: &tx_broadcaster,
7456                         default_config: UserConfig::default(),
7457                         channel_monitors,
7458                 }).unwrap().1
7459         };
7460         nodes[0].node = &node_state_0;
7461         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7462         nodes[0].chain_monitor = &monitor;
7463         nodes[0].chain_source = &chain_source;
7464
7465         check_added_monitors!(nodes[0], 1);
7466
7467         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7468         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7469
7470         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7471
7472         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7473         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7474         check_added_monitors!(nodes[0], 1);
7475
7476         {
7477                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7478                 assert_eq!(node_txn.len(), 0);
7479         }
7480
7481         let mut reestablish_1 = Vec::with_capacity(1);
7482         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7483                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7484                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7485                         reestablish_1.push(msg.clone());
7486                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7487                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7488                         match action {
7489                                 &ErrorAction::SendErrorMessage { ref msg } => {
7490                                         assert_eq!(msg.data, "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can't do any automated broadcasting");
7491                                 },
7492                                 _ => panic!("Unexpected event!"),
7493                         }
7494                 } else {
7495                         panic!("Unexpected event")
7496                 }
7497         }
7498
7499         // Check we close channel detecting A is fallen-behind
7500         // Check that we sent the warning message when we detected that A has fallen behind,
7501         // and give the possibility for A to recover from the warning.
7502         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7503         let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7504         assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7505
7506         // Check A is able to claim to_remote output
7507         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7508         // The node B should not broadcast the transaction to force close the channel!
7509         assert!(node_txn.is_empty());
7510         // B should now detect that there is something wrong and should force close the channel.
7511         let exp_err = "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can\'t do any automated broadcasting";
7512         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: exp_err.to_string() });
7513
7514         // after the warning message sent by B, we should not able to
7515         // use the channel, or reconnect with success to the channel.
7516         assert!(nodes[0].node.list_usable_channels().is_empty());
7517         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7518         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7519         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7520
7521         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7522         let mut err_msgs_0 = Vec::with_capacity(1);
7523         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7524                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7525                         match action {
7526                                 &ErrorAction::SendErrorMessage { ref msg } => {
7527                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7528                                         err_msgs_0.push(msg.clone());
7529                                 },
7530                                 _ => panic!("Unexpected event!"),
7531                         }
7532                 } else {
7533                         panic!("Unexpected event!");
7534                 }
7535         }
7536         assert_eq!(err_msgs_0.len(), 1);
7537         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7538         assert!(nodes[1].node.list_usable_channels().is_empty());
7539         check_added_monitors!(nodes[1], 1);
7540         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7541         check_closed_broadcast!(nodes[1], false);
7542 }
7543
7544 #[test]
7545 fn test_check_htlc_underpaying() {
7546         // Send payment through A -> B but A is maliciously
7547         // sending a probe payment (i.e less than expected value0
7548         // to B, B should refuse payment.
7549
7550         let chanmon_cfgs = create_chanmon_cfgs(2);
7551         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7552         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7553         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7554
7555         // Create some initial channels
7556         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7557
7558         let scorer = test_utils::TestScorer::with_penalty(0);
7559         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7560         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7561         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();
7562         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7563         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7564         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7565         check_added_monitors!(nodes[0], 1);
7566
7567         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7568         assert_eq!(events.len(), 1);
7569         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7570         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7571         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7572
7573         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7574         // and then will wait a second random delay before failing the HTLC back:
7575         expect_pending_htlcs_forwardable!(nodes[1]);
7576         expect_pending_htlcs_forwardable!(nodes[1]);
7577
7578         // Node 3 is expecting payment of 100_000 but received 10_000,
7579         // it should fail htlc like we didn't know the preimage.
7580         nodes[1].node.process_pending_htlc_forwards();
7581
7582         let events = nodes[1].node.get_and_clear_pending_msg_events();
7583         assert_eq!(events.len(), 1);
7584         let (update_fail_htlc, commitment_signed) = match events[0] {
7585                 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 } } => {
7586                         assert!(update_add_htlcs.is_empty());
7587                         assert!(update_fulfill_htlcs.is_empty());
7588                         assert_eq!(update_fail_htlcs.len(), 1);
7589                         assert!(update_fail_malformed_htlcs.is_empty());
7590                         assert!(update_fee.is_none());
7591                         (update_fail_htlcs[0].clone(), commitment_signed)
7592                 },
7593                 _ => panic!("Unexpected event"),
7594         };
7595         check_added_monitors!(nodes[1], 1);
7596
7597         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7598         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7599
7600         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7601         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7602         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7603         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7604 }
7605
7606 #[test]
7607 fn test_announce_disable_channels() {
7608         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7609         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7610
7611         let chanmon_cfgs = create_chanmon_cfgs(2);
7612         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7613         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7614         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7615
7616         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7617         create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7618         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7619
7620         // Disconnect peers
7621         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7622         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7623
7624         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7625         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7626         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7627         assert_eq!(msg_events.len(), 3);
7628         let mut chans_disabled = HashMap::new();
7629         for e in msg_events {
7630                 match e {
7631                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7632                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7633                                 // Check that each channel gets updated exactly once
7634                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7635                                         panic!("Generated ChannelUpdate for wrong chan!");
7636                                 }
7637                         },
7638                         _ => panic!("Unexpected event"),
7639                 }
7640         }
7641         // Reconnect peers
7642         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7643         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7644         assert_eq!(reestablish_1.len(), 3);
7645         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7646         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7647         assert_eq!(reestablish_2.len(), 3);
7648
7649         // Reestablish chan_1
7650         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7651         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7652         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7653         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7654         // Reestablish chan_2
7655         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7656         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7657         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7658         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7659         // Reestablish chan_3
7660         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7661         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7662         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7663         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7664
7665         nodes[0].node.timer_tick_occurred();
7666         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7667         nodes[0].node.timer_tick_occurred();
7668         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7669         assert_eq!(msg_events.len(), 3);
7670         for e in msg_events {
7671                 match e {
7672                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7673                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7674                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7675                                         // Each update should have a higher timestamp than the previous one, replacing
7676                                         // the old one.
7677                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7678                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7679                                 }
7680                         },
7681                         _ => panic!("Unexpected event"),
7682                 }
7683         }
7684         // Check that each channel gets updated exactly once
7685         assert!(chans_disabled.is_empty());
7686 }
7687
7688 #[test]
7689 fn test_bump_penalty_txn_on_revoked_commitment() {
7690         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7691         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7692
7693         let chanmon_cfgs = create_chanmon_cfgs(2);
7694         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7695         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7696         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7697
7698         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7699
7700         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7701         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7702                 .with_features(InvoiceFeatures::known());
7703         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7704         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7705
7706         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7707         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7708         assert_eq!(revoked_txn[0].output.len(), 4);
7709         assert_eq!(revoked_txn[0].input.len(), 1);
7710         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7711         let revoked_txid = revoked_txn[0].txid();
7712
7713         let mut penalty_sum = 0;
7714         for outp in revoked_txn[0].output.iter() {
7715                 if outp.script_pubkey.is_v0_p2wsh() {
7716                         penalty_sum += outp.value;
7717                 }
7718         }
7719
7720         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7721         let header_114 = connect_blocks(&nodes[1], 14);
7722
7723         // Actually revoke tx by claiming a HTLC
7724         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7725         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7726         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7727         check_added_monitors!(nodes[1], 1);
7728
7729         // One or more justice tx should have been broadcast, check it
7730         let penalty_1;
7731         let feerate_1;
7732         {
7733                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7734                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7735                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7736                 assert_eq!(node_txn[0].output.len(), 1);
7737                 check_spends!(node_txn[0], revoked_txn[0]);
7738                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7739                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7740                 penalty_1 = node_txn[0].txid();
7741                 node_txn.clear();
7742         };
7743
7744         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7745         connect_blocks(&nodes[1], 15);
7746         let mut penalty_2 = penalty_1;
7747         let mut feerate_2 = 0;
7748         {
7749                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7750                 assert_eq!(node_txn.len(), 1);
7751                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
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                         penalty_2 = node_txn[0].txid();
7756                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7757                         assert_ne!(penalty_2, penalty_1);
7758                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7759                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7760                         // Verify 25% bump heuristic
7761                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7762                         node_txn.clear();
7763                 }
7764         }
7765         assert_ne!(feerate_2, 0);
7766
7767         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7768         connect_blocks(&nodes[1], 1);
7769         let penalty_3;
7770         let mut feerate_3 = 0;
7771         {
7772                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7773                 assert_eq!(node_txn.len(), 1);
7774                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7775                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7776                         assert_eq!(node_txn[0].output.len(), 1);
7777                         check_spends!(node_txn[0], revoked_txn[0]);
7778                         penalty_3 = node_txn[0].txid();
7779                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7780                         assert_ne!(penalty_3, penalty_2);
7781                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7782                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7783                         // Verify 25% bump heuristic
7784                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7785                         node_txn.clear();
7786                 }
7787         }
7788         assert_ne!(feerate_3, 0);
7789
7790         nodes[1].node.get_and_clear_pending_events();
7791         nodes[1].node.get_and_clear_pending_msg_events();
7792 }
7793
7794 #[test]
7795 fn test_bump_penalty_txn_on_revoked_htlcs() {
7796         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7797         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7798
7799         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7800         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7801         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7802         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7803         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7804
7805         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7806         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7807         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7808         let scorer = test_utils::TestScorer::with_penalty(0);
7809         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7810         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7811                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7812         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7813         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7814         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7815                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7816         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7817
7818         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7819         assert_eq!(revoked_local_txn[0].input.len(), 1);
7820         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7821
7822         // Revoke local commitment tx
7823         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7824
7825         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7826         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7827         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7828         check_closed_broadcast!(nodes[1], true);
7829         check_added_monitors!(nodes[1], 1);
7830         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7831         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7832
7833         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7834         assert_eq!(revoked_htlc_txn.len(), 3);
7835         check_spends!(revoked_htlc_txn[1], chan.3);
7836
7837         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7838         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7839         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7840
7841         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7842         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7843         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7844         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7845
7846         // Broadcast set of revoked txn on A
7847         let hash_128 = connect_blocks(&nodes[0], 40);
7848         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7849         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7850         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7851         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7852         let events = nodes[0].node.get_and_clear_pending_events();
7853         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7854         match events[1] {
7855                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7856                 _ => panic!("Unexpected event"),
7857         }
7858         let first;
7859         let feerate_1;
7860         let penalty_txn;
7861         {
7862                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7863                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7864                 // Verify claim tx are spending revoked HTLC txn
7865
7866                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7867                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7868                 // which are included in the same block (they are broadcasted because we scan the
7869                 // transactions linearly and generate claims as we go, they likely should be removed in the
7870                 // future).
7871                 assert_eq!(node_txn[0].input.len(), 1);
7872                 check_spends!(node_txn[0], revoked_local_txn[0]);
7873                 assert_eq!(node_txn[1].input.len(), 1);
7874                 check_spends!(node_txn[1], revoked_local_txn[0]);
7875                 assert_eq!(node_txn[2].input.len(), 1);
7876                 check_spends!(node_txn[2], revoked_local_txn[0]);
7877
7878                 // Each of the three justice transactions claim a separate (single) output of the three
7879                 // available, which we check here:
7880                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7881                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7882                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7883
7884                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7885                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7886
7887                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7888                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7889                 // a remote commitment tx has already been confirmed).
7890                 check_spends!(node_txn[3], chan.3);
7891
7892                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7893                 // output, checked above).
7894                 assert_eq!(node_txn[4].input.len(), 2);
7895                 assert_eq!(node_txn[4].output.len(), 1);
7896                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7897
7898                 first = node_txn[4].txid();
7899                 // Store both feerates for later comparison
7900                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7901                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7902                 penalty_txn = vec![node_txn[2].clone()];
7903                 node_txn.clear();
7904         }
7905
7906         // Connect one more block to see if bumped penalty are issued for HTLC txn
7907         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7908         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7909         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7910         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7911         {
7912                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7913                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7914
7915                 check_spends!(node_txn[0], revoked_local_txn[0]);
7916                 check_spends!(node_txn[1], revoked_local_txn[0]);
7917                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7918                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7919                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7920                 } else {
7921                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7922                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7923                 }
7924
7925                 node_txn.clear();
7926         };
7927
7928         // Few more blocks to confirm penalty txn
7929         connect_blocks(&nodes[0], 4);
7930         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7931         let header_144 = connect_blocks(&nodes[0], 9);
7932         let node_txn = {
7933                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7934                 assert_eq!(node_txn.len(), 1);
7935
7936                 assert_eq!(node_txn[0].input.len(), 2);
7937                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7938                 // Verify bumped tx is different and 25% bump heuristic
7939                 assert_ne!(first, node_txn[0].txid());
7940                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7941                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7942                 assert!(feerate_2 * 100 > feerate_1 * 125);
7943                 let txn = vec![node_txn[0].clone()];
7944                 node_txn.clear();
7945                 txn
7946         };
7947         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7948         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7949         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7950         connect_blocks(&nodes[0], 20);
7951         {
7952                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7953                 // We verify than no new transaction has been broadcast because previously
7954                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7955                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7956                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7957                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7958                 // up bumped justice generation.
7959                 assert_eq!(node_txn.len(), 0);
7960                 node_txn.clear();
7961         }
7962         check_closed_broadcast!(nodes[0], true);
7963         check_added_monitors!(nodes[0], 1);
7964 }
7965
7966 #[test]
7967 fn test_bump_penalty_txn_on_remote_commitment() {
7968         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7969         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7970
7971         // Create 2 HTLCs
7972         // Provide preimage for one
7973         // Check aggregation
7974
7975         let chanmon_cfgs = create_chanmon_cfgs(2);
7976         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7977         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7978         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7979
7980         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7981         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7982         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7983
7984         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7985         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7986         assert_eq!(remote_txn[0].output.len(), 4);
7987         assert_eq!(remote_txn[0].input.len(), 1);
7988         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7989
7990         // Claim a HTLC without revocation (provide B monitor with preimage)
7991         nodes[1].node.claim_funds(payment_preimage);
7992         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7993         mine_transaction(&nodes[1], &remote_txn[0]);
7994         check_added_monitors!(nodes[1], 2);
7995         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7996
7997         // One or more claim tx should have been broadcast, check it
7998         let timeout;
7999         let preimage;
8000         let preimage_bump;
8001         let feerate_timeout;
8002         let feerate_preimage;
8003         {
8004                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8005                 // 9 transactions including:
8006                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8007                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8008                 // 2 * HTLC-Success (one RBF bump we'll check later)
8009                 // 1 * HTLC-Timeout
8010                 assert_eq!(node_txn.len(), 8);
8011                 assert_eq!(node_txn[0].input.len(), 1);
8012                 assert_eq!(node_txn[6].input.len(), 1);
8013                 check_spends!(node_txn[0], remote_txn[0]);
8014                 check_spends!(node_txn[6], remote_txn[0]);
8015
8016                 check_spends!(node_txn[1], chan.3);
8017                 check_spends!(node_txn[2], node_txn[1]);
8018
8019                 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
8020                         preimage_bump = node_txn[3].clone();
8021                         check_spends!(node_txn[3], remote_txn[0]);
8022
8023                         assert_eq!(node_txn[1], node_txn[4]);
8024                         assert_eq!(node_txn[2], node_txn[5]);
8025                 } else {
8026                         preimage_bump = node_txn[7].clone();
8027                         check_spends!(node_txn[7], remote_txn[0]);
8028                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8029
8030                         assert_eq!(node_txn[1], node_txn[3]);
8031                         assert_eq!(node_txn[2], node_txn[4]);
8032                 }
8033
8034                 timeout = node_txn[6].txid();
8035                 let index = node_txn[6].input[0].previous_output.vout;
8036                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8037                 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8038
8039                 preimage = node_txn[0].txid();
8040                 let index = node_txn[0].input[0].previous_output.vout;
8041                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8042                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8043
8044                 node_txn.clear();
8045         };
8046         assert_ne!(feerate_timeout, 0);
8047         assert_ne!(feerate_preimage, 0);
8048
8049         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8050         connect_blocks(&nodes[1], 15);
8051         {
8052                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8053                 assert_eq!(node_txn.len(), 1);
8054                 assert_eq!(node_txn[0].input.len(), 1);
8055                 assert_eq!(preimage_bump.input.len(), 1);
8056                 check_spends!(node_txn[0], remote_txn[0]);
8057                 check_spends!(preimage_bump, remote_txn[0]);
8058
8059                 let index = preimage_bump.input[0].previous_output.vout;
8060                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8061                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8062                 assert!(new_feerate * 100 > feerate_timeout * 125);
8063                 assert_ne!(timeout, preimage_bump.txid());
8064
8065                 let index = node_txn[0].input[0].previous_output.vout;
8066                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8067                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8068                 assert!(new_feerate * 100 > feerate_preimage * 125);
8069                 assert_ne!(preimage, node_txn[0].txid());
8070
8071                 node_txn.clear();
8072         }
8073
8074         nodes[1].node.get_and_clear_pending_events();
8075         nodes[1].node.get_and_clear_pending_msg_events();
8076 }
8077
8078 #[test]
8079 fn test_counterparty_raa_skip_no_crash() {
8080         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8081         // commitment transaction, we would have happily carried on and provided them the next
8082         // commitment transaction based on one RAA forward. This would probably eventually have led to
8083         // channel closure, but it would not have resulted in funds loss. Still, our
8084         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8085         // check simply that the channel is closed in response to such an RAA, but don't check whether
8086         // we decide to punish our counterparty for revoking their funds (as we don't currently
8087         // implement that).
8088         let chanmon_cfgs = create_chanmon_cfgs(2);
8089         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8090         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8091         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8092         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8093
8094         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8095         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8096
8097         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8098
8099         // Make signer believe we got a counterparty signature, so that it allows the revocation
8100         keys.get_enforcement_state().last_holder_commitment -= 1;
8101         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8102
8103         // Must revoke without gaps
8104         keys.get_enforcement_state().last_holder_commitment -= 1;
8105         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8106
8107         keys.get_enforcement_state().last_holder_commitment -= 1;
8108         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8109                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8110
8111         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8112                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8113         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8114         check_added_monitors!(nodes[1], 1);
8115         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8116 }
8117
8118 #[test]
8119 fn test_bump_txn_sanitize_tracking_maps() {
8120         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8121         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8122
8123         let chanmon_cfgs = create_chanmon_cfgs(2);
8124         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8125         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8126         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8127
8128         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8129         // Lock HTLC in both directions
8130         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8131         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8132
8133         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8134         assert_eq!(revoked_local_txn[0].input.len(), 1);
8135         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8136
8137         // Revoke local commitment tx
8138         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8139
8140         // Broadcast set of revoked txn on A
8141         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8142         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8143         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8144
8145         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8146         check_closed_broadcast!(nodes[0], true);
8147         check_added_monitors!(nodes[0], 1);
8148         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8149         let penalty_txn = {
8150                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8151                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8152                 check_spends!(node_txn[0], revoked_local_txn[0]);
8153                 check_spends!(node_txn[1], revoked_local_txn[0]);
8154                 check_spends!(node_txn[2], revoked_local_txn[0]);
8155                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8156                 node_txn.clear();
8157                 penalty_txn
8158         };
8159         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8160         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8161         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8162         {
8163                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8164                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8165                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8166         }
8167 }
8168
8169 #[test]
8170 fn test_pending_claimed_htlc_no_balance_underflow() {
8171         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8172         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8173         let chanmon_cfgs = create_chanmon_cfgs(2);
8174         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8175         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8176         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8177         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8178
8179         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8180         nodes[1].node.claim_funds(payment_preimage);
8181         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8182         check_added_monitors!(nodes[1], 1);
8183         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8184
8185         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8186         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8187         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8188         check_added_monitors!(nodes[0], 1);
8189         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8190
8191         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8192         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8193         // can get our balance.
8194
8195         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8196         // the public key of the only hop. This works around ChannelDetails not showing the
8197         // almost-claimed HTLC as available balance.
8198         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8199         route.payment_params = None; // This is all wrong, but unnecessary
8200         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8201         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8202         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8203
8204         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8205 }
8206
8207 #[test]
8208 fn test_channel_conf_timeout() {
8209         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8210         // confirm within 2016 blocks, as recommended by BOLT 2.
8211         let chanmon_cfgs = create_chanmon_cfgs(2);
8212         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8213         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8214         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8215
8216         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8217
8218         // The outbound node should wait forever for confirmation:
8219         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8220         // copied here instead of directly referencing the constant.
8221         connect_blocks(&nodes[0], 2016);
8222         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8223
8224         // The inbound node should fail the channel after exactly 2016 blocks
8225         connect_blocks(&nodes[1], 2015);
8226         check_added_monitors!(nodes[1], 0);
8227         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8228
8229         connect_blocks(&nodes[1], 1);
8230         check_added_monitors!(nodes[1], 1);
8231         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8232         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8233         assert_eq!(close_ev.len(), 1);
8234         match close_ev[0] {
8235                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8236                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8237                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8238                 },
8239                 _ => panic!("Unexpected event"),
8240         }
8241 }
8242
8243 #[test]
8244 fn test_override_channel_config() {
8245         let chanmon_cfgs = create_chanmon_cfgs(2);
8246         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8247         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8248         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8249
8250         // Node0 initiates a channel to node1 using the override config.
8251         let mut override_config = UserConfig::default();
8252         override_config.channel_handshake_config.our_to_self_delay = 200;
8253
8254         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8255
8256         // Assert the channel created by node0 is using the override config.
8257         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8258         assert_eq!(res.channel_flags, 0);
8259         assert_eq!(res.to_self_delay, 200);
8260 }
8261
8262 #[test]
8263 fn test_override_0msat_htlc_minimum() {
8264         let mut zero_config = UserConfig::default();
8265         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8266         let chanmon_cfgs = create_chanmon_cfgs(2);
8267         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8268         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8269         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8270
8271         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8272         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8273         assert_eq!(res.htlc_minimum_msat, 1);
8274
8275         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8276         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8277         assert_eq!(res.htlc_minimum_msat, 1);
8278 }
8279
8280 #[test]
8281 fn test_channel_update_has_correct_htlc_maximum_msat() {
8282         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8283         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8284         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8285         // 90% of the `channel_value`.
8286         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8287
8288         let mut config_30_percent = UserConfig::default();
8289         config_30_percent.channel_handshake_config.announced_channel = true;
8290         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8291         let mut config_50_percent = UserConfig::default();
8292         config_50_percent.channel_handshake_config.announced_channel = true;
8293         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8294         let mut config_95_percent = UserConfig::default();
8295         config_95_percent.channel_handshake_config.announced_channel = true;
8296         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8297         let mut config_100_percent = UserConfig::default();
8298         config_100_percent.channel_handshake_config.announced_channel = true;
8299         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8300
8301         let chanmon_cfgs = create_chanmon_cfgs(4);
8302         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8303         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)]);
8304         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8305
8306         let channel_value_satoshis = 100000;
8307         let channel_value_msat = channel_value_satoshis * 1000;
8308         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8309         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8310         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8311
8312         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());
8313         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());
8314
8315         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8316         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8317         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8318         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8319         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8320         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8321
8322         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8323         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8324         // `channel_value`.
8325         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8326         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8327         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8328         // `channel_value`.
8329         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8330 }
8331
8332 #[test]
8333 fn test_manually_accept_inbound_channel_request() {
8334         let mut manually_accept_conf = UserConfig::default();
8335         manually_accept_conf.manually_accept_inbound_channels = true;
8336         let chanmon_cfgs = create_chanmon_cfgs(2);
8337         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8338         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8339         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8340
8341         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8342         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8343
8344         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8345
8346         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8347         // accepting the inbound channel request.
8348         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8349
8350         let events = nodes[1].node.get_and_clear_pending_events();
8351         match events[0] {
8352                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8353                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8354                 }
8355                 _ => panic!("Unexpected event"),
8356         }
8357
8358         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8359         assert_eq!(accept_msg_ev.len(), 1);
8360
8361         match accept_msg_ev[0] {
8362                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8363                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8364                 }
8365                 _ => panic!("Unexpected event"),
8366         }
8367
8368         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8369
8370         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8371         assert_eq!(close_msg_ev.len(), 1);
8372
8373         let events = nodes[1].node.get_and_clear_pending_events();
8374         match events[0] {
8375                 Event::ChannelClosed { user_channel_id, .. } => {
8376                         assert_eq!(user_channel_id, 23);
8377                 }
8378                 _ => panic!("Unexpected event"),
8379         }
8380 }
8381
8382 #[test]
8383 fn test_manually_reject_inbound_channel_request() {
8384         let mut manually_accept_conf = UserConfig::default();
8385         manually_accept_conf.manually_accept_inbound_channels = true;
8386         let chanmon_cfgs = create_chanmon_cfgs(2);
8387         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8388         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8389         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8390
8391         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8392         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8393
8394         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8395
8396         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8397         // rejecting the inbound channel request.
8398         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8399
8400         let events = nodes[1].node.get_and_clear_pending_events();
8401         match events[0] {
8402                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8403                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8404                 }
8405                 _ => panic!("Unexpected event"),
8406         }
8407
8408         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8409         assert_eq!(close_msg_ev.len(), 1);
8410
8411         match close_msg_ev[0] {
8412                 MessageSendEvent::HandleError { ref node_id, .. } => {
8413                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8414                 }
8415                 _ => panic!("Unexpected event"),
8416         }
8417         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8418 }
8419
8420 #[test]
8421 fn test_reject_funding_before_inbound_channel_accepted() {
8422         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8423         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8424         // the node operator before the counterparty sends a `FundingCreated` message. If a
8425         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8426         // and the channel should be closed.
8427         let mut manually_accept_conf = UserConfig::default();
8428         manually_accept_conf.manually_accept_inbound_channels = true;
8429         let chanmon_cfgs = create_chanmon_cfgs(2);
8430         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8431         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8432         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8433
8434         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8435         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8436         let temp_channel_id = res.temporary_channel_id;
8437
8438         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8439
8440         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8441         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8442
8443         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8444         nodes[1].node.get_and_clear_pending_events();
8445
8446         // Get the `AcceptChannel` message of `nodes[1]` without calling
8447         // `ChannelManager::accept_inbound_channel`, which generates a
8448         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8449         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8450         // succeed when `nodes[0]` is passed to it.
8451         {
8452                 let mut lock;
8453                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8454                 let accept_chan_msg = channel.get_accept_channel_message();
8455                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8456         }
8457
8458         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8459
8460         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8461         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8462
8463         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8464         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8465
8466         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8467         assert_eq!(close_msg_ev.len(), 1);
8468
8469         let expected_err = "FundingCreated message received before the channel was accepted";
8470         match close_msg_ev[0] {
8471                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8472                         assert_eq!(msg.channel_id, temp_channel_id);
8473                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8474                         assert_eq!(msg.data, expected_err);
8475                 }
8476                 _ => panic!("Unexpected event"),
8477         }
8478
8479         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8480 }
8481
8482 #[test]
8483 fn test_can_not_accept_inbound_channel_twice() {
8484         let mut manually_accept_conf = UserConfig::default();
8485         manually_accept_conf.manually_accept_inbound_channels = true;
8486         let chanmon_cfgs = create_chanmon_cfgs(2);
8487         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8488         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8489         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8490
8491         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8492         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8493
8494         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8495
8496         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8497         // accepting the inbound channel request.
8498         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8499
8500         let events = nodes[1].node.get_and_clear_pending_events();
8501         match events[0] {
8502                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8503                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8504                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8505                         match api_res {
8506                                 Err(APIError::APIMisuseError { err }) => {
8507                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8508                                 },
8509                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8510                                 Err(_) => panic!("Unexpected Error"),
8511                         }
8512                 }
8513                 _ => panic!("Unexpected event"),
8514         }
8515
8516         // Ensure that the channel wasn't closed after attempting to accept it twice.
8517         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8518         assert_eq!(accept_msg_ev.len(), 1);
8519
8520         match accept_msg_ev[0] {
8521                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8522                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8523                 }
8524                 _ => panic!("Unexpected event"),
8525         }
8526 }
8527
8528 #[test]
8529 fn test_can_not_accept_unknown_inbound_channel() {
8530         let chanmon_cfg = create_chanmon_cfgs(2);
8531         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8532         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8533         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8534
8535         let unknown_channel_id = [0; 32];
8536         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8537         match api_res {
8538                 Err(APIError::ChannelUnavailable { err }) => {
8539                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8540                 },
8541                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8542                 Err(_) => panic!("Unexpected Error"),
8543         }
8544 }
8545
8546 #[test]
8547 fn test_simple_mpp() {
8548         // Simple test of sending a multi-path payment.
8549         let chanmon_cfgs = create_chanmon_cfgs(4);
8550         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8551         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8552         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8553
8554         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8555         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8556         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8557         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8558
8559         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8560         let path = route.paths[0].clone();
8561         route.paths.push(path);
8562         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8563         route.paths[0][0].short_channel_id = chan_1_id;
8564         route.paths[0][1].short_channel_id = chan_3_id;
8565         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8566         route.paths[1][0].short_channel_id = chan_2_id;
8567         route.paths[1][1].short_channel_id = chan_4_id;
8568         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8569         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8570 }
8571
8572 #[test]
8573 fn test_preimage_storage() {
8574         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8575         let chanmon_cfgs = create_chanmon_cfgs(2);
8576         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8577         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8578         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8579
8580         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8581
8582         {
8583                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8584                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8585                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8586                 check_added_monitors!(nodes[0], 1);
8587                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8588                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8589                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8590                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8591         }
8592         // Note that after leaving the above scope we have no knowledge of any arguments or return
8593         // values from previous calls.
8594         expect_pending_htlcs_forwardable!(nodes[1]);
8595         let events = nodes[1].node.get_and_clear_pending_events();
8596         assert_eq!(events.len(), 1);
8597         match events[0] {
8598                 Event::PaymentReceived { ref purpose, .. } => {
8599                         match &purpose {
8600                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8601                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8602                                 },
8603                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8604                         }
8605                 },
8606                 _ => panic!("Unexpected event"),
8607         }
8608 }
8609
8610 #[test]
8611 #[allow(deprecated)]
8612 fn test_secret_timeout() {
8613         // Simple test of payment secret storage time outs. After
8614         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8615         let chanmon_cfgs = create_chanmon_cfgs(2);
8616         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8617         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8618         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8619
8620         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8621
8622         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8623
8624         // We should fail to register the same payment hash twice, at least until we've connected a
8625         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8626         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8627                 assert_eq!(err, "Duplicate payment hash");
8628         } else { panic!(); }
8629         let mut block = {
8630                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8631                 Block {
8632                         header: BlockHeader {
8633                                 version: 0x2000000,
8634                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8635                                 merkle_root: Default::default(),
8636                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8637                         txdata: vec![],
8638                 }
8639         };
8640         connect_block(&nodes[1], &block);
8641         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8642                 assert_eq!(err, "Duplicate payment hash");
8643         } else { panic!(); }
8644
8645         // If we then connect the second block, we should be able to register the same payment hash
8646         // again (this time getting a new payment secret).
8647         block.header.prev_blockhash = block.header.block_hash();
8648         block.header.time += 1;
8649         connect_block(&nodes[1], &block);
8650         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8651         assert_ne!(payment_secret_1, our_payment_secret);
8652
8653         {
8654                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8655                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8656                 check_added_monitors!(nodes[0], 1);
8657                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8658                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8659                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8660                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8661         }
8662         // Note that after leaving the above scope we have no knowledge of any arguments or return
8663         // values from previous calls.
8664         expect_pending_htlcs_forwardable!(nodes[1]);
8665         let events = nodes[1].node.get_and_clear_pending_events();
8666         assert_eq!(events.len(), 1);
8667         match events[0] {
8668                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8669                         assert!(payment_preimage.is_none());
8670                         assert_eq!(payment_secret, our_payment_secret);
8671                         // We don't actually have the payment preimage with which to claim this payment!
8672                 },
8673                 _ => panic!("Unexpected event"),
8674         }
8675 }
8676
8677 #[test]
8678 fn test_bad_secret_hash() {
8679         // Simple test of unregistered payment hash/invalid payment secret handling
8680         let chanmon_cfgs = create_chanmon_cfgs(2);
8681         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8682         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8683         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8684
8685         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8686
8687         let random_payment_hash = PaymentHash([42; 32]);
8688         let random_payment_secret = PaymentSecret([43; 32]);
8689         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8690         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8691
8692         // All the below cases should end up being handled exactly identically, so we macro the
8693         // resulting events.
8694         macro_rules! handle_unknown_invalid_payment_data {
8695                 () => {
8696                         check_added_monitors!(nodes[0], 1);
8697                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8698                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8699                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8700                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8701
8702                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8703                         // again to process the pending backwards-failure of the HTLC
8704                         expect_pending_htlcs_forwardable!(nodes[1]);
8705                         expect_pending_htlcs_forwardable!(nodes[1]);
8706                         check_added_monitors!(nodes[1], 1);
8707
8708                         // We should fail the payment back
8709                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8710                         match events.pop().unwrap() {
8711                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8712                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8713                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8714                                 },
8715                                 _ => panic!("Unexpected event"),
8716                         }
8717                 }
8718         }
8719
8720         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8721         // Error data is the HTLC value (100,000) and current block height
8722         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8723
8724         // Send a payment with the right payment hash but the wrong payment secret
8725         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8726         handle_unknown_invalid_payment_data!();
8727         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8728
8729         // Send a payment with a random payment hash, but the right payment secret
8730         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8731         handle_unknown_invalid_payment_data!();
8732         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8733
8734         // Send a payment with a random payment hash and random payment secret
8735         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8736         handle_unknown_invalid_payment_data!();
8737         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8738 }
8739
8740 #[test]
8741 fn test_update_err_monitor_lockdown() {
8742         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8743         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8744         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8745         //
8746         // This scenario may happen in a watchtower setup, where watchtower process a block height
8747         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8748         // commitment at same time.
8749
8750         let chanmon_cfgs = create_chanmon_cfgs(2);
8751         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8752         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8753         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8754
8755         // Create some initial channel
8756         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8757         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8758
8759         // Rebalance the network to generate htlc in the two directions
8760         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8761
8762         // Route a HTLC from node 0 to node 1 (but don't settle)
8763         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8764
8765         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8766         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8767         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8768         let persister = test_utils::TestPersister::new();
8769         let watchtower = {
8770                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8771                 let mut w = test_utils::TestVecWriter(Vec::new());
8772                 monitor.write(&mut w).unwrap();
8773                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8774                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8775                 assert!(new_monitor == *monitor);
8776                 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);
8777                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8778                 watchtower
8779         };
8780         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8781         let block = Block { header, txdata: vec![] };
8782         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8783         // transaction lock time requirements here.
8784         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8785         watchtower.chain_monitor.block_connected(&block, 200);
8786
8787         // Try to update ChannelMonitor
8788         nodes[1].node.claim_funds(preimage);
8789         check_added_monitors!(nodes[1], 1);
8790         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8791
8792         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8793         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8794         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8795         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8796                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8797                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8798                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8799                 } else { assert!(false); }
8800         } else { assert!(false); };
8801         // Our local monitor is in-sync and hasn't processed yet timeout
8802         check_added_monitors!(nodes[0], 1);
8803         let events = nodes[0].node.get_and_clear_pending_events();
8804         assert_eq!(events.len(), 1);
8805 }
8806
8807 #[test]
8808 fn test_concurrent_monitor_claim() {
8809         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8810         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8811         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8812         // state N+1 confirms. Alice claims output from state N+1.
8813
8814         let chanmon_cfgs = create_chanmon_cfgs(2);
8815         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8816         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8817         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8818
8819         // Create some initial channel
8820         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8821         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8822
8823         // Rebalance the network to generate htlc in the two directions
8824         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8825
8826         // Route a HTLC from node 0 to node 1 (but don't settle)
8827         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8828
8829         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8830         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8831         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8832         let persister = test_utils::TestPersister::new();
8833         let watchtower_alice = {
8834                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8835                 let mut w = test_utils::TestVecWriter(Vec::new());
8836                 monitor.write(&mut w).unwrap();
8837                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8838                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8839                 assert!(new_monitor == *monitor);
8840                 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);
8841                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8842                 watchtower
8843         };
8844         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8845         let block = Block { header, txdata: vec![] };
8846         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8847         // transaction lock time requirements here.
8848         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));
8849         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8850
8851         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8852         {
8853                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8854                 assert_eq!(txn.len(), 2);
8855                 txn.clear();
8856         }
8857
8858         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8859         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8860         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8861         let persister = test_utils::TestPersister::new();
8862         let watchtower_bob = {
8863                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8864                 let mut w = test_utils::TestVecWriter(Vec::new());
8865                 monitor.write(&mut w).unwrap();
8866                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8867                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8868                 assert!(new_monitor == *monitor);
8869                 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);
8870                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8871                 watchtower
8872         };
8873         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8874         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8875
8876         // Route another payment to generate another update with still previous HTLC pending
8877         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8878         {
8879                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8880         }
8881         check_added_monitors!(nodes[1], 1);
8882
8883         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8884         assert_eq!(updates.update_add_htlcs.len(), 1);
8885         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8886         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8887                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8888                         // Watchtower Alice should already have seen the block and reject the update
8889                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8890                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8891                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8892                 } else { assert!(false); }
8893         } else { assert!(false); };
8894         // Our local monitor is in-sync and hasn't processed yet timeout
8895         check_added_monitors!(nodes[0], 1);
8896
8897         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8898         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8899         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8900
8901         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8902         let bob_state_y;
8903         {
8904                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8905                 assert_eq!(txn.len(), 2);
8906                 bob_state_y = txn[0].clone();
8907                 txn.clear();
8908         };
8909
8910         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8911         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8912         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);
8913         {
8914                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8915                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8916                 // the onchain detection of the HTLC output
8917                 assert_eq!(htlc_txn.len(), 2);
8918                 check_spends!(htlc_txn[0], bob_state_y);
8919                 check_spends!(htlc_txn[1], bob_state_y);
8920         }
8921 }
8922
8923 #[test]
8924 fn test_pre_lockin_no_chan_closed_update() {
8925         // Test that if a peer closes a channel in response to a funding_created message we don't
8926         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8927         // message).
8928         //
8929         // Doing so would imply a channel monitor update before the initial channel monitor
8930         // registration, violating our API guarantees.
8931         //
8932         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8933         // then opening a second channel with the same funding output as the first (which is not
8934         // rejected because the first channel does not exist in the ChannelManager) and closing it
8935         // before receiving funding_signed.
8936         let chanmon_cfgs = create_chanmon_cfgs(2);
8937         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8938         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8939         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8940
8941         // Create an initial channel
8942         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8943         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8944         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8945         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8946         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8947
8948         // Move the first channel through the funding flow...
8949         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8950
8951         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8952         check_added_monitors!(nodes[0], 0);
8953
8954         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8955         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8956         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8957         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8958         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8959 }
8960
8961 #[test]
8962 fn test_htlc_no_detection() {
8963         // This test is a mutation to underscore the detection logic bug we had
8964         // before #653. HTLC value routed is above the remaining balance, thus
8965         // inverting HTLC and `to_remote` output. HTLC will come second and
8966         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8967         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8968         // outputs order detection for correct spending children filtring.
8969
8970         let chanmon_cfgs = create_chanmon_cfgs(2);
8971         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8972         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8973         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8974
8975         // Create some initial channels
8976         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8977
8978         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8979         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8980         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8981         assert_eq!(local_txn[0].input.len(), 1);
8982         assert_eq!(local_txn[0].output.len(), 3);
8983         check_spends!(local_txn[0], chan_1.3);
8984
8985         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8986         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8987         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8988         // We deliberately connect the local tx twice as this should provoke a failure calling
8989         // this test before #653 fix.
8990         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);
8991         check_closed_broadcast!(nodes[0], true);
8992         check_added_monitors!(nodes[0], 1);
8993         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8994         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8995
8996         let htlc_timeout = {
8997                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8998                 assert_eq!(node_txn[1].input.len(), 1);
8999                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9000                 check_spends!(node_txn[1], local_txn[0]);
9001                 node_txn[1].clone()
9002         };
9003
9004         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9005         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9006         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9007         expect_payment_failed!(nodes[0], our_payment_hash, true);
9008 }
9009
9010 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9011         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9012         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9013         // Carol, Alice would be the upstream node, and Carol the downstream.)
9014         //
9015         // Steps of the test:
9016         // 1) Alice sends a HTLC to Carol through Bob.
9017         // 2) Carol doesn't settle the HTLC.
9018         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9019         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9020         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9021         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9022         // 5) Carol release the preimage to Bob off-chain.
9023         // 6) Bob claims the offered output on the broadcasted commitment.
9024         let chanmon_cfgs = create_chanmon_cfgs(3);
9025         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9026         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9027         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9028
9029         // Create some initial channels
9030         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9031         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9032
9033         // Steps (1) and (2):
9034         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9035         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9036
9037         // Check that Alice's commitment transaction now contains an output for this HTLC.
9038         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9039         check_spends!(alice_txn[0], chan_ab.3);
9040         assert_eq!(alice_txn[0].output.len(), 2);
9041         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9042         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9043         assert_eq!(alice_txn.len(), 2);
9044
9045         // Steps (3) and (4):
9046         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9047         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9048         let mut force_closing_node = 0; // Alice force-closes
9049         let mut counterparty_node = 1; // Bob if Alice force-closes
9050
9051         // Bob force-closes
9052         if !broadcast_alice {
9053                 force_closing_node = 1;
9054                 counterparty_node = 0;
9055         }
9056         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9057         check_closed_broadcast!(nodes[force_closing_node], true);
9058         check_added_monitors!(nodes[force_closing_node], 1);
9059         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9060         if go_onchain_before_fulfill {
9061                 let txn_to_broadcast = match broadcast_alice {
9062                         true => alice_txn.clone(),
9063                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9064                 };
9065                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9066                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9067                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9068                 if broadcast_alice {
9069                         check_closed_broadcast!(nodes[1], true);
9070                         check_added_monitors!(nodes[1], 1);
9071                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9072                 }
9073                 assert_eq!(bob_txn.len(), 1);
9074                 check_spends!(bob_txn[0], chan_ab.3);
9075         }
9076
9077         // Step (5):
9078         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9079         // process of removing the HTLC from their commitment transactions.
9080         nodes[2].node.claim_funds(payment_preimage);
9081         check_added_monitors!(nodes[2], 1);
9082         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9083
9084         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9085         assert!(carol_updates.update_add_htlcs.is_empty());
9086         assert!(carol_updates.update_fail_htlcs.is_empty());
9087         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9088         assert!(carol_updates.update_fee.is_none());
9089         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9090
9091         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9092         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9093         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9094         if !go_onchain_before_fulfill && broadcast_alice {
9095                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9096                 assert_eq!(events.len(), 1);
9097                 match events[0] {
9098                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9099                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9100                         },
9101                         _ => panic!("Unexpected event"),
9102                 };
9103         }
9104         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9105         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9106         // Carol<->Bob's updated commitment transaction info.
9107         check_added_monitors!(nodes[1], 2);
9108
9109         let events = nodes[1].node.get_and_clear_pending_msg_events();
9110         assert_eq!(events.len(), 2);
9111         let bob_revocation = match events[0] {
9112                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9113                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9114                         (*msg).clone()
9115                 },
9116                 _ => panic!("Unexpected event"),
9117         };
9118         let bob_updates = match events[1] {
9119                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9120                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9121                         (*updates).clone()
9122                 },
9123                 _ => panic!("Unexpected event"),
9124         };
9125
9126         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9127         check_added_monitors!(nodes[2], 1);
9128         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9129         check_added_monitors!(nodes[2], 1);
9130
9131         let events = nodes[2].node.get_and_clear_pending_msg_events();
9132         assert_eq!(events.len(), 1);
9133         let carol_revocation = match events[0] {
9134                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9135                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9136                         (*msg).clone()
9137                 },
9138                 _ => panic!("Unexpected event"),
9139         };
9140         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9141         check_added_monitors!(nodes[1], 1);
9142
9143         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9144         // here's where we put said channel's commitment tx on-chain.
9145         let mut txn_to_broadcast = alice_txn.clone();
9146         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9147         if !go_onchain_before_fulfill {
9148                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9149                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9150                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9151                 if broadcast_alice {
9152                         check_closed_broadcast!(nodes[1], true);
9153                         check_added_monitors!(nodes[1], 1);
9154                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9155                 }
9156                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9157                 if broadcast_alice {
9158                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9159                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9160                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9161                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9162                         // broadcasted.
9163                         assert_eq!(bob_txn.len(), 3);
9164                         check_spends!(bob_txn[1], chan_ab.3);
9165                 } else {
9166                         assert_eq!(bob_txn.len(), 2);
9167                         check_spends!(bob_txn[0], chan_ab.3);
9168                 }
9169         }
9170
9171         // Step (6):
9172         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9173         // broadcasted commitment transaction.
9174         {
9175                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9176                 if go_onchain_before_fulfill {
9177                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9178                         assert_eq!(bob_txn.len(), 2);
9179                 }
9180                 let script_weight = match broadcast_alice {
9181                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9182                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9183                 };
9184                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9185                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9186                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9187                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9188                 if broadcast_alice && !go_onchain_before_fulfill {
9189                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9190                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9191                 } else {
9192                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9193                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9194                 }
9195         }
9196 }
9197
9198 #[test]
9199 fn test_onchain_htlc_settlement_after_close() {
9200         do_test_onchain_htlc_settlement_after_close(true, true);
9201         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9202         do_test_onchain_htlc_settlement_after_close(true, false);
9203         do_test_onchain_htlc_settlement_after_close(false, false);
9204 }
9205
9206 #[test]
9207 fn test_duplicate_chan_id() {
9208         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9209         // already open we reject it and keep the old channel.
9210         //
9211         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9212         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9213         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9214         // updating logic for the existing channel.
9215         let chanmon_cfgs = create_chanmon_cfgs(2);
9216         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9217         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9218         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9219
9220         // Create an initial channel
9221         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9222         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9223         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9224         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()));
9225
9226         // Try to create a second channel with the same temporary_channel_id as the first and check
9227         // that it is rejected.
9228         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9229         {
9230                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9231                 assert_eq!(events.len(), 1);
9232                 match events[0] {
9233                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9234                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9235                                 // first (valid) and second (invalid) channels are closed, given they both have
9236                                 // the same non-temporary channel_id. However, currently we do not, so we just
9237                                 // move forward with it.
9238                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9239                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9240                         },
9241                         _ => panic!("Unexpected event"),
9242                 }
9243         }
9244
9245         // Move the first channel through the funding flow...
9246         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9247
9248         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9249         check_added_monitors!(nodes[0], 0);
9250
9251         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9252         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9253         {
9254                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9255                 assert_eq!(added_monitors.len(), 1);
9256                 assert_eq!(added_monitors[0].0, funding_output);
9257                 added_monitors.clear();
9258         }
9259         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9260
9261         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9262         let channel_id = funding_outpoint.to_channel_id();
9263
9264         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9265         // temporary one).
9266
9267         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9268         // Technically this is allowed by the spec, but we don't support it and there's little reason
9269         // to. Still, it shouldn't cause any other issues.
9270         open_chan_msg.temporary_channel_id = channel_id;
9271         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9272         {
9273                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9274                 assert_eq!(events.len(), 1);
9275                 match events[0] {
9276                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9277                                 // Technically, at this point, nodes[1] would be justified in thinking both
9278                                 // channels are closed, but currently we do not, so we just move forward with it.
9279                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9280                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9281                         },
9282                         _ => panic!("Unexpected event"),
9283                 }
9284         }
9285
9286         // Now try to create a second channel which has a duplicate funding output.
9287         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9288         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9289         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9290         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()));
9291         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9292
9293         let funding_created = {
9294                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9295                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9296                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9297                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9298                 // channelmanager in a possibly nonsense state instead).
9299                 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9300                 let logger = test_utils::TestLogger::new();
9301                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9302         };
9303         check_added_monitors!(nodes[0], 0);
9304         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9305         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9306         // still needs to be cleared here.
9307         check_added_monitors!(nodes[1], 1);
9308
9309         // ...still, nodes[1] will reject the duplicate channel.
9310         {
9311                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9312                 assert_eq!(events.len(), 1);
9313                 match events[0] {
9314                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9315                                 // Technically, at this point, nodes[1] would be justified in thinking both
9316                                 // channels are closed, but currently we do not, so we just move forward with it.
9317                                 assert_eq!(msg.channel_id, channel_id);
9318                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9319                         },
9320                         _ => panic!("Unexpected event"),
9321                 }
9322         }
9323
9324         // finally, finish creating the original channel and send a payment over it to make sure
9325         // everything is functional.
9326         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9327         {
9328                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9329                 assert_eq!(added_monitors.len(), 1);
9330                 assert_eq!(added_monitors[0].0, funding_output);
9331                 added_monitors.clear();
9332         }
9333
9334         let events_4 = nodes[0].node.get_and_clear_pending_events();
9335         assert_eq!(events_4.len(), 0);
9336         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9337         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9338
9339         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9340         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9341         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9342         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9343 }
9344
9345 #[test]
9346 fn test_error_chans_closed() {
9347         // Test that we properly handle error messages, closing appropriate channels.
9348         //
9349         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9350         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9351         // we can test various edge cases around it to ensure we don't regress.
9352         let chanmon_cfgs = create_chanmon_cfgs(3);
9353         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9354         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9355         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9356
9357         // Create some initial channels
9358         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9359         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9360         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9361
9362         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9363         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9364         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9365
9366         // Closing a channel from a different peer has no effect
9367         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9368         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9369
9370         // Closing one channel doesn't impact others
9371         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9372         check_added_monitors!(nodes[0], 1);
9373         check_closed_broadcast!(nodes[0], false);
9374         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9375         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9376         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9377         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);
9378         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);
9379
9380         // A null channel ID should close all channels
9381         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9382         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9383         check_added_monitors!(nodes[0], 2);
9384         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9385         let events = nodes[0].node.get_and_clear_pending_msg_events();
9386         assert_eq!(events.len(), 2);
9387         match events[0] {
9388                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9389                         assert_eq!(msg.contents.flags & 2, 2);
9390                 },
9391                 _ => panic!("Unexpected event"),
9392         }
9393         match events[1] {
9394                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9395                         assert_eq!(msg.contents.flags & 2, 2);
9396                 },
9397                 _ => panic!("Unexpected event"),
9398         }
9399         // Note that at this point users of a standard PeerHandler will end up calling
9400         // peer_disconnected with no_connection_possible set to false, duplicating the
9401         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9402         // users with their own peer handling logic. We duplicate the call here, however.
9403         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9404         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9405
9406         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9407         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9408         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9409 }
9410
9411 #[test]
9412 fn test_invalid_funding_tx() {
9413         // Test that we properly handle invalid funding transactions sent to us from a peer.
9414         //
9415         // Previously, all other major lightning implementations had failed to properly sanitize
9416         // funding transactions from their counterparties, leading to a multi-implementation critical
9417         // security vulnerability (though we always sanitized properly, we've previously had
9418         // un-released crashes in the sanitization process).
9419         let chanmon_cfgs = create_chanmon_cfgs(2);
9420         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9421         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9422         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9423
9424         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9425         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()));
9426         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()));
9427
9428         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9429         for output in tx.output.iter_mut() {
9430                 // Make the confirmed funding transaction have a bogus script_pubkey
9431                 output.script_pubkey = bitcoin::Script::new();
9432         }
9433
9434         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9435         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()));
9436         check_added_monitors!(nodes[1], 1);
9437
9438         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()));
9439         check_added_monitors!(nodes[0], 1);
9440
9441         let events_1 = nodes[0].node.get_and_clear_pending_events();
9442         assert_eq!(events_1.len(), 0);
9443
9444         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9445         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9446         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9447
9448         let expected_err = "funding tx had wrong script/value or output index";
9449         confirm_transaction_at(&nodes[1], &tx, 1);
9450         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9451         check_added_monitors!(nodes[1], 1);
9452         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9453         assert_eq!(events_2.len(), 1);
9454         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9455                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9456                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9457                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9458                 } else { panic!(); }
9459         } else { panic!(); }
9460         assert_eq!(nodes[1].node.list_channels().len(), 0);
9461 }
9462
9463 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9464         // In the first version of the chain::Confirm interface, after a refactor was made to not
9465         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9466         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9467         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9468         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9469         // spending transaction until height N+1 (or greater). This was due to the way
9470         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9471         // spending transaction at the height the input transaction was confirmed at, not whether we
9472         // should broadcast a spending transaction at the current height.
9473         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9474         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9475         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9476         // until we learned about an additional block.
9477         //
9478         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9479         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9480         let chanmon_cfgs = create_chanmon_cfgs(3);
9481         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9482         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9483         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9484         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9485
9486         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9487         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9488         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9489         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9490         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9491
9492         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9493         check_closed_broadcast!(nodes[1], true);
9494         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9495         check_added_monitors!(nodes[1], 1);
9496         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9497         assert_eq!(node_txn.len(), 1);
9498
9499         let conf_height = nodes[1].best_block_info().1;
9500         if !test_height_before_timelock {
9501                 connect_blocks(&nodes[1], 24 * 6);
9502         }
9503         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9504                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9505         if test_height_before_timelock {
9506                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9507                 // generate any events or broadcast any transactions
9508                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9509                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9510         } else {
9511                 // We should broadcast an HTLC transaction spending our funding transaction first
9512                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9513                 assert_eq!(spending_txn.len(), 2);
9514                 assert_eq!(spending_txn[0], node_txn[0]);
9515                 check_spends!(spending_txn[1], node_txn[0]);
9516                 // We should also generate a SpendableOutputs event with the to_self output (as its
9517                 // timelock is up).
9518                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9519                 assert_eq!(descriptor_spend_txn.len(), 1);
9520
9521                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9522                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9523                 // additional block built on top of the current chain.
9524                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9525                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9526                 expect_pending_htlcs_forwardable!(nodes[1]);
9527                 check_added_monitors!(nodes[1], 1);
9528
9529                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9530                 assert!(updates.update_add_htlcs.is_empty());
9531                 assert!(updates.update_fulfill_htlcs.is_empty());
9532                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9533                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9534                 assert!(updates.update_fee.is_none());
9535                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9536                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9537                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9538         }
9539 }
9540
9541 #[test]
9542 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9543         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9544         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9545 }
9546
9547 #[test]
9548 fn test_forwardable_regen() {
9549         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9550         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9551         // HTLCs.
9552         // We test it for both payment receipt and payment forwarding.
9553
9554         let chanmon_cfgs = create_chanmon_cfgs(3);
9555         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9556         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9557         let persister: test_utils::TestPersister;
9558         let new_chain_monitor: test_utils::TestChainMonitor;
9559         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9560         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9561         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9562         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9563
9564         // First send a payment to nodes[1]
9565         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9566         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9567         check_added_monitors!(nodes[0], 1);
9568
9569         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9570         assert_eq!(events.len(), 1);
9571         let payment_event = SendEvent::from_event(events.pop().unwrap());
9572         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9573         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9574
9575         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9576
9577         // Next send a payment which is forwarded by nodes[1]
9578         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9579         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9580         check_added_monitors!(nodes[0], 1);
9581
9582         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9583         assert_eq!(events.len(), 1);
9584         let payment_event = SendEvent::from_event(events.pop().unwrap());
9585         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9586         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9587
9588         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9589         // generated
9590         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9591
9592         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9593         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9594         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9595
9596         let nodes_1_serialized = nodes[1].node.encode();
9597         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9598         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9599         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9600         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9601
9602         persister = test_utils::TestPersister::new();
9603         let keys_manager = &chanmon_cfgs[1].keys_manager;
9604         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);
9605         nodes[1].chain_monitor = &new_chain_monitor;
9606
9607         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9608         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9609                 &mut chan_0_monitor_read, keys_manager).unwrap();
9610         assert!(chan_0_monitor_read.is_empty());
9611         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9612         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9613                 &mut chan_1_monitor_read, keys_manager).unwrap();
9614         assert!(chan_1_monitor_read.is_empty());
9615
9616         let mut nodes_1_read = &nodes_1_serialized[..];
9617         let (_, nodes_1_deserialized_tmp) = {
9618                 let mut channel_monitors = HashMap::new();
9619                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9620                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9621                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9622                         default_config: UserConfig::default(),
9623                         keys_manager,
9624                         fee_estimator: node_cfgs[1].fee_estimator,
9625                         chain_monitor: nodes[1].chain_monitor,
9626                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9627                         logger: nodes[1].logger,
9628                         channel_monitors,
9629                 }).unwrap()
9630         };
9631         nodes_1_deserialized = nodes_1_deserialized_tmp;
9632         assert!(nodes_1_read.is_empty());
9633
9634         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9635         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9636         nodes[1].node = &nodes_1_deserialized;
9637         check_added_monitors!(nodes[1], 2);
9638
9639         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9640         // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9641         // the commitment state.
9642         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9643
9644         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9645
9646         expect_pending_htlcs_forwardable!(nodes[1]);
9647         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9648         check_added_monitors!(nodes[1], 1);
9649
9650         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9651         assert_eq!(events.len(), 1);
9652         let payment_event = SendEvent::from_event(events.pop().unwrap());
9653         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9654         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9655         expect_pending_htlcs_forwardable!(nodes[2]);
9656         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9657
9658         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9659         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9660 }
9661
9662 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9663         let chanmon_cfgs = create_chanmon_cfgs(2);
9664         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9665         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9666         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9667
9668         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9669
9670         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9671                 .with_features(InvoiceFeatures::known());
9672         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9673
9674         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9675
9676         {
9677                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9678                 check_added_monitors!(nodes[0], 1);
9679                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9680                 assert_eq!(events.len(), 1);
9681                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9682                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9683                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9684         }
9685         expect_pending_htlcs_forwardable!(nodes[1]);
9686         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9687
9688         {
9689                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9690                 check_added_monitors!(nodes[0], 1);
9691                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9692                 assert_eq!(events.len(), 1);
9693                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9694                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9695                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9696                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9697                 // assume the second is a privacy attack (no longer particularly relevant
9698                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9699                 // the first HTLC delivered above.
9700         }
9701
9702         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9703         nodes[1].node.process_pending_htlc_forwards();
9704
9705         if test_for_second_fail_panic {
9706                 // Now we go fail back the first HTLC from the user end.
9707                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9708
9709                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9710                 nodes[1].node.process_pending_htlc_forwards();
9711
9712                 check_added_monitors!(nodes[1], 1);
9713                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9714                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9715
9716                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9717                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9718                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9719
9720                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9721                 assert_eq!(failure_events.len(), 2);
9722                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9723                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9724         } else {
9725                 // Let the second HTLC fail and claim the first
9726                 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9727                 nodes[1].node.process_pending_htlc_forwards();
9728
9729                 check_added_monitors!(nodes[1], 1);
9730                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9731                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9732                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9733
9734                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9735
9736                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9737         }
9738 }
9739
9740 #[test]
9741 fn test_dup_htlc_second_fail_panic() {
9742         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9743         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9744         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9745         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9746         do_test_dup_htlc_second_rejected(true);
9747 }
9748
9749 #[test]
9750 fn test_dup_htlc_second_rejected() {
9751         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9752         // simply reject the second HTLC but are still able to claim the first HTLC.
9753         do_test_dup_htlc_second_rejected(false);
9754 }
9755
9756 #[test]
9757 fn test_inconsistent_mpp_params() {
9758         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9759         // such HTLC and allow the second to stay.
9760         let chanmon_cfgs = create_chanmon_cfgs(4);
9761         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9762         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9763         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9764
9765         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9766         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9767         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9768         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9769
9770         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9771                 .with_features(InvoiceFeatures::known());
9772         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9773         assert_eq!(route.paths.len(), 2);
9774         route.paths.sort_by(|path_a, _| {
9775                 // Sort the path so that the path through nodes[1] comes first
9776                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9777                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9778         });
9779         let payment_params_opt = Some(payment_params);
9780
9781         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9782
9783         let cur_height = nodes[0].best_block_info().1;
9784         let payment_id = PaymentId([42; 32]);
9785         {
9786                 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();
9787                 check_added_monitors!(nodes[0], 1);
9788
9789                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9790                 assert_eq!(events.len(), 1);
9791                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9792         }
9793         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9794
9795         {
9796                 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();
9797                 check_added_monitors!(nodes[0], 1);
9798
9799                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9800                 assert_eq!(events.len(), 1);
9801                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9802
9803                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9804                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9805
9806                 expect_pending_htlcs_forwardable!(nodes[2]);
9807                 check_added_monitors!(nodes[2], 1);
9808
9809                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9810                 assert_eq!(events.len(), 1);
9811                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9812
9813                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9814                 check_added_monitors!(nodes[3], 0);
9815                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9816
9817                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9818                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9819                 // post-payment_secrets) and fail back the new HTLC.
9820         }
9821         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9822         nodes[3].node.process_pending_htlc_forwards();
9823         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9824         nodes[3].node.process_pending_htlc_forwards();
9825
9826         check_added_monitors!(nodes[3], 1);
9827
9828         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9829         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9830         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9831
9832         expect_pending_htlcs_forwardable!(nodes[2]);
9833         check_added_monitors!(nodes[2], 1);
9834
9835         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9836         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9837         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9838
9839         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9840
9841         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();
9842         check_added_monitors!(nodes[0], 1);
9843
9844         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9845         assert_eq!(events.len(), 1);
9846         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9847
9848         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9849 }
9850
9851 #[test]
9852 fn test_keysend_payments_to_public_node() {
9853         let chanmon_cfgs = create_chanmon_cfgs(2);
9854         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9855         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9856         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9857
9858         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9859         let network_graph = nodes[0].network_graph;
9860         let payer_pubkey = nodes[0].node.get_our_node_id();
9861         let payee_pubkey = nodes[1].node.get_our_node_id();
9862         let route_params = RouteParameters {
9863                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9864                 final_value_msat: 10000,
9865                 final_cltv_expiry_delta: 40,
9866         };
9867         let scorer = test_utils::TestScorer::with_penalty(0);
9868         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9869         let route = find_route(&payer_pubkey, &route_params, &network_graph.read_only(), None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9870
9871         let test_preimage = PaymentPreimage([42; 32]);
9872         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9873         check_added_monitors!(nodes[0], 1);
9874         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9875         assert_eq!(events.len(), 1);
9876         let event = events.pop().unwrap();
9877         let path = vec![&nodes[1]];
9878         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9879         claim_payment(&nodes[0], &path, test_preimage);
9880 }
9881
9882 #[test]
9883 fn test_keysend_payments_to_private_node() {
9884         let chanmon_cfgs = create_chanmon_cfgs(2);
9885         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9886         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9887         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9888
9889         let payer_pubkey = nodes[0].node.get_our_node_id();
9890         let payee_pubkey = nodes[1].node.get_our_node_id();
9891         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9892         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9893
9894         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9895         let route_params = RouteParameters {
9896                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9897                 final_value_msat: 10000,
9898                 final_cltv_expiry_delta: 40,
9899         };
9900         let network_graph = nodes[0].network_graph;
9901         let first_hops = nodes[0].node.list_usable_channels();
9902         let scorer = test_utils::TestScorer::with_penalty(0);
9903         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9904         let route = find_route(
9905                 &payer_pubkey, &route_params, &network_graph.read_only(),
9906                 Some(&first_hops.iter().collect::<Vec<_>>()), nodes[0].logger, &scorer, &random_seed_bytes
9907         ).unwrap();
9908
9909         let test_preimage = PaymentPreimage([42; 32]);
9910         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9911         check_added_monitors!(nodes[0], 1);
9912         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9913         assert_eq!(events.len(), 1);
9914         let event = events.pop().unwrap();
9915         let path = vec![&nodes[1]];
9916         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9917         claim_payment(&nodes[0], &path, test_preimage);
9918 }
9919
9920 #[test]
9921 fn test_double_partial_claim() {
9922         // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9923         // time out, the sender resends only some of the MPP parts, then the user processes the
9924         // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9925         // amount.
9926         let chanmon_cfgs = create_chanmon_cfgs(4);
9927         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9928         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9929         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9930
9931         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9932         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9933         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9934         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9935
9936         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9937         assert_eq!(route.paths.len(), 2);
9938         route.paths.sort_by(|path_a, _| {
9939                 // Sort the path so that the path through nodes[1] comes first
9940                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9941                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9942         });
9943
9944         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9945         // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
9946         // amount of time to respond to.
9947
9948         // Connect some blocks to time out the payment
9949         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9950         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9951
9952         expect_pending_htlcs_forwardable!(nodes[3]);
9953
9954         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9955
9956         // nodes[1] now retries one of the two paths...
9957         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9958         check_added_monitors!(nodes[0], 2);
9959
9960         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9961         assert_eq!(events.len(), 2);
9962         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
9963
9964         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9965         // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
9966         nodes[3].node.claim_funds(payment_preimage);
9967         check_added_monitors!(nodes[3], 0);
9968         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9969 }
9970
9971 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
9972         // Test what happens if a node receives an MPP payment, claims it, but crashes before
9973         // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
9974         // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
9975         // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
9976         // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
9977         // not have the preimage tied to the still-pending HTLC.
9978         //
9979         // To get to the correct state, on startup we should propagate the preimage to the
9980         // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
9981         // receiving the preimage without a state update.
9982         //
9983         // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
9984         // definitely claimed.
9985         let chanmon_cfgs = create_chanmon_cfgs(4);
9986         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9987         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9988
9989         let persister: test_utils::TestPersister;
9990         let new_chain_monitor: test_utils::TestChainMonitor;
9991         let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9992
9993         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9994
9995         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9996         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9997         let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
9998         let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
9999
10000         // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10001         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10002         assert_eq!(route.paths.len(), 2);
10003         route.paths.sort_by(|path_a, _| {
10004                 // Sort the path so that the path through nodes[1] comes first
10005                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10006                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10007         });
10008
10009         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10010         check_added_monitors!(nodes[0], 2);
10011
10012         // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10013         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10014         assert_eq!(send_events.len(), 2);
10015         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);
10016         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);
10017
10018         // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10019         // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10020         let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10021         if !persist_both_monitors {
10022                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10023                         if outpoint.to_channel_id() == chan_id_not_persisted {
10024                                 assert!(original_monitor.0.is_empty());
10025                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10026                         }
10027                 }
10028         }
10029
10030         let mut original_manager = test_utils::TestVecWriter(Vec::new());
10031         nodes[3].node.write(&mut original_manager).unwrap();
10032
10033         expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10034
10035         nodes[3].node.claim_funds(payment_preimage);
10036         check_added_monitors!(nodes[3], 2);
10037         expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10038
10039         // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10040         // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10041         // with the old ChannelManager.
10042         let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10043         for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10044                 if outpoint.to_channel_id() == chan_id_persisted {
10045                         assert!(updated_monitor.0.is_empty());
10046                         nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10047                 }
10048         }
10049         // If `persist_both_monitors` is set, get the second monitor here as well
10050         if persist_both_monitors {
10051                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10052                         if outpoint.to_channel_id() == chan_id_not_persisted {
10053                                 assert!(original_monitor.0.is_empty());
10054                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10055                         }
10056                 }
10057         }
10058
10059         // Now restart nodes[3].
10060         persister = test_utils::TestPersister::new();
10061         let keys_manager = &chanmon_cfgs[3].keys_manager;
10062         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);
10063         nodes[3].chain_monitor = &new_chain_monitor;
10064         let mut monitors = Vec::new();
10065         for mut monitor_data in [original_monitor, updated_monitor].iter() {
10066                 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10067                 monitors.push(deserialized_monitor);
10068         }
10069
10070         let config = UserConfig::default();
10071         nodes_3_deserialized = {
10072                 let mut channel_monitors = HashMap::new();
10073                 for monitor in monitors.iter_mut() {
10074                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10075                 }
10076                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10077                         default_config: config,
10078                         keys_manager,
10079                         fee_estimator: node_cfgs[3].fee_estimator,
10080                         chain_monitor: nodes[3].chain_monitor,
10081                         tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10082                         logger: nodes[3].logger,
10083                         channel_monitors,
10084                 }).unwrap().1
10085         };
10086         nodes[3].node = &nodes_3_deserialized;
10087
10088         for monitor in monitors {
10089                 // On startup the preimage should have been copied into the non-persisted monitor:
10090                 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10091                 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10092         }
10093         check_added_monitors!(nodes[3], 2);
10094
10095         nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10096         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10097
10098         // During deserialization, we should have closed one channel and broadcast its latest
10099         // commitment transaction. We should also still have the original PaymentReceived event we
10100         // never finished processing.
10101         let events = nodes[3].node.get_and_clear_pending_events();
10102         assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10103         if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10104         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10105         if persist_both_monitors {
10106                 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10107         }
10108
10109         // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10110         // ChannelManager prior to handling the original one.
10111         if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10112                 events[if persist_both_monitors { 3 } else { 2 }]
10113         {
10114                 assert_eq!(payment_hash, our_payment_hash);
10115         } else { panic!(); }
10116
10117         assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10118         if !persist_both_monitors {
10119                 // If one of the two channels is still live, reveal the payment preimage over it.
10120
10121                 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10122                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10123                 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10124                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10125
10126                 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10127                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10128                 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10129
10130                 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10131
10132                 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10133                 // claim should fly.
10134                 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10135                 check_added_monitors!(nodes[3], 1);
10136                 assert_eq!(ds_msgs.len(), 2);
10137                 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10138
10139                 let cs_updates = match ds_msgs[0] {
10140                         MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10141                                 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10142                                 check_added_monitors!(nodes[2], 1);
10143                                 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10144                                 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10145                                 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10146                                 cs_updates
10147                         }
10148                         _ => panic!(),
10149                 };
10150
10151                 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10152                 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10153                 expect_payment_sent!(nodes[0], payment_preimage);
10154         }
10155 }
10156
10157 #[test]
10158 fn test_partial_claim_before_restart() {
10159         do_test_partial_claim_before_restart(false);
10160         do_test_partial_claim_before_restart(true);
10161 }
10162
10163 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10164 #[derive(Clone, Copy, PartialEq)]
10165 enum ExposureEvent {
10166         /// Breach occurs at HTLC forwarding (see `send_htlc`)
10167         AtHTLCForward,
10168         /// Breach occurs at HTLC reception (see `update_add_htlc`)
10169         AtHTLCReception,
10170         /// Breach occurs at outbound update_fee (see `send_update_fee`)
10171         AtUpdateFeeOutbound,
10172 }
10173
10174 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10175         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10176         // policy.
10177         //
10178         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10179         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10180         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10181         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10182         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10183         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10184         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10185         // might be available again for HTLC processing once the dust bandwidth has cleared up.
10186
10187         let chanmon_cfgs = create_chanmon_cfgs(2);
10188         let mut config = test_default_channel_config();
10189         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10190         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10191         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10192         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10193
10194         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10195         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10196         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10197         open_channel.max_accepted_htlcs = 60;
10198         if on_holder_tx {
10199                 open_channel.dust_limit_satoshis = 546;
10200         }
10201         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10202         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10203         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10204
10205         let opt_anchors = false;
10206
10207         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10208
10209         if on_holder_tx {
10210                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10211                         chan.holder_dust_limit_satoshis = 546;
10212                 }
10213         }
10214
10215         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10216         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()));
10217         check_added_monitors!(nodes[1], 1);
10218
10219         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()));
10220         check_added_monitors!(nodes[0], 1);
10221
10222         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10223         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10224         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10225
10226         let dust_buffer_feerate = {
10227                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10228                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10229                 chan.get_dust_buffer_feerate(None) as u64
10230         };
10231         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;
10232         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10233
10234         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;
10235         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10236
10237         let dust_htlc_on_counterparty_tx: u64 = 25;
10238         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10239
10240         if on_holder_tx {
10241                 if dust_outbound_balance {
10242                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10243                         // Outbound dust balance: 4372 sats
10244                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10245                         for i in 0..dust_outbound_htlc_on_holder_tx {
10246                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10247                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10248                         }
10249                 } else {
10250                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10251                         // Inbound dust balance: 4372 sats
10252                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10253                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10254                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10255                         }
10256                 }
10257         } else {
10258                 if dust_outbound_balance {
10259                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10260                         // Outbound dust balance: 5000 sats
10261                         for i in 0..dust_htlc_on_counterparty_tx {
10262                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10263                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10264                         }
10265                 } else {
10266                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10267                         // Inbound dust balance: 5000 sats
10268                         for _ in 0..dust_htlc_on_counterparty_tx {
10269                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10270                         }
10271                 }
10272         }
10273
10274         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10275         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10276                 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 });
10277                 let mut config = UserConfig::default();
10278                 // With default dust exposure: 5000 sats
10279                 if on_holder_tx {
10280                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10281                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10282                         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)));
10283                 } else {
10284                         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)));
10285                 }
10286         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10287                 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 });
10288                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10289                 check_added_monitors!(nodes[1], 1);
10290                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10291                 assert_eq!(events.len(), 1);
10292                 let payment_event = SendEvent::from_event(events.remove(0));
10293                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10294                 // With default dust exposure: 5000 sats
10295                 if on_holder_tx {
10296                         // Outbound dust balance: 6399 sats
10297                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10298                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10299                         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);
10300                 } else {
10301                         // Outbound dust balance: 5200 sats
10302                         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);
10303                 }
10304         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10305                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10306                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10307                 {
10308                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10309                         *feerate_lock = *feerate_lock * 10;
10310                 }
10311                 nodes[0].node.timer_tick_occurred();
10312                 check_added_monitors!(nodes[0], 1);
10313                 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);
10314         }
10315
10316         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10317         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10318         added_monitors.clear();
10319 }
10320
10321 #[test]
10322 fn test_max_dust_htlc_exposure() {
10323         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10324         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10325         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10326         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10327         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10328         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10329         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10330         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10331         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10332         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10333         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10334         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10335 }
10336
10337 #[test]
10338 fn test_non_final_funding_tx() {
10339         let chanmon_cfgs = create_chanmon_cfgs(2);
10340         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10341         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10342         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10343
10344         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10345         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10346         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
10347         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10348         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
10349
10350         let best_height = nodes[0].node.best_block.read().unwrap().height();
10351
10352         let chan_id = *nodes[0].network_chan_count.borrow();
10353         let events = nodes[0].node.get_and_clear_pending_events();
10354         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: 0x1, witness: Witness::from_vec(vec!(vec!(1))) };
10355         assert_eq!(events.len(), 1);
10356         let mut tx = match events[0] {
10357                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10358                         // Timelock the transaction _beyond_ the best client height + 2.
10359                         Transaction { version: chan_id as i32, lock_time: best_height + 3, input: vec![input], output: vec![TxOut {
10360                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10361                         }]}
10362                 },
10363                 _ => panic!("Unexpected event"),
10364         };
10365         // Transaction should fail as it's evaluated as non-final for propagation.
10366         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10367                 Err(APIError::APIMisuseError { err }) => {
10368                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10369                 },
10370                 _ => panic!()
10371         }
10372
10373         // However, transaction should be accepted if it's in a +2 headroom from best block.
10374         tx.lock_time -= 1;
10375         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10376         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10377 }