Merge pull request #1619 from G8XSU/main
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use chain;
15 use chain::{Confirm, Listen, Watch};
16 use chain::chaininterface::LowerBoundedFeeEstimator;
17 use chain::channelmonitor;
18 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use chain::transaction::OutPoint;
20 use chain::keysinterface::{BaseSign, KeysInterface};
21 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
22 use ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
23 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS };
24 use ln::channel::{Channel, ChannelError};
25 use ln::{chan_utils, onion_utils};
26 use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
27 use routing::gossip::NetworkGraph;
28 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
29 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
30 use ln::msgs;
31 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
32 use util::enforcing_trait_impls::EnforcingSigner;
33 use util::{byte_utils, test_utils};
34 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason, HTLCDestination};
35 use util::errors::APIError;
36 use util::ser::{Writeable, ReadableArgs};
37 use util::config::UserConfig;
38
39 use bitcoin::hash_types::BlockHash;
40 use bitcoin::blockdata::block::{Block, BlockHeader};
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
47
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
50
51 use regex;
52
53 use io;
54 use prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use sync::{Arc, Mutex};
59
60 use ln::functional_test_utils::*;
61 use ln::chan_utils::CommitmentTransaction;
62
63 #[test]
64 fn test_insane_channel_opens() {
65         // Stand up a network of 2 nodes
66         use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
67         let mut cfg = UserConfig::default();
68         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
69         let chanmon_cfgs = create_chanmon_cfgs(2);
70         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
71         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
72         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
73
74         // Instantiate channel parameters where we push the maximum msats given our
75         // funding satoshis
76         let channel_value_sat = 31337; // same as funding satoshis
77         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
78         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
79
80         // Have node0 initiate a channel to node1 with aforementioned parameters
81         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
82
83         // Extract the channel open message from node0 to node1
84         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
85
86         // Test helper that asserts we get the correct error string given a mutator
87         // that supposedly makes the channel open message insane
88         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
89                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
90                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
91                 assert_eq!(msg_events.len(), 1);
92                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
93                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
94                         match action {
95                                 &ErrorAction::SendErrorMessage { .. } => {
96                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
97                                 },
98                                 _ => panic!("unexpected event!"),
99                         }
100                 } else { assert!(false); }
101         };
102
103         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
104
105         // Test all mutations that would make the channel open message insane
106         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 });
107         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 });
108
109         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
110
111         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 });
112
113         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
114
115         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 });
116
117         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 });
118
119         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
120
121         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
122 }
123
124 #[test]
125 fn test_funding_exceeds_no_wumbo_limit() {
126         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
127         // them.
128         use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
129         let chanmon_cfgs = create_chanmon_cfgs(2);
130         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
131         node_cfgs[1].features = InitFeatures::known().clear_wumbo();
132         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
133         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
134
135         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
136                 Err(APIError::APIMisuseError { err }) => {
137                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
138                 },
139                 _ => panic!()
140         }
141 }
142
143 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
144         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
145         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
146         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
147         // in normal testing, we test it explicitly here.
148         let chanmon_cfgs = create_chanmon_cfgs(2);
149         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
150         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
151         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
152         let default_config = UserConfig::default();
153
154         // Have node0 initiate a channel to node1 with aforementioned parameters
155         let mut push_amt = 100_000_000;
156         let feerate_per_kw = 253;
157         let opt_anchors = false;
158         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
159         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
160
161         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();
162         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
163         if !send_from_initiator {
164                 open_channel_message.channel_reserve_satoshis = 0;
165                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
166         }
167         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
168
169         // Extract the channel accept message from node1 to node0
170         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
171         if send_from_initiator {
172                 accept_channel_message.channel_reserve_satoshis = 0;
173                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
174         }
175         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
176         {
177                 let mut lock;
178                 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
179                 chan.holder_selected_channel_reserve_satoshis = 0;
180                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
181         }
182
183         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
184         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
185         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
186
187         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
188         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
189         if send_from_initiator {
190                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
191                         // Note that for outbound channels we have to consider the commitment tx fee and the
192                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
193                         // well as an additional HTLC.
194                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
195         } else {
196                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
197         }
198 }
199
200 #[test]
201 fn test_counterparty_no_reserve() {
202         do_test_counterparty_no_reserve(true);
203         do_test_counterparty_no_reserve(false);
204 }
205
206 #[test]
207 fn test_async_inbound_update_fee() {
208         let chanmon_cfgs = create_chanmon_cfgs(2);
209         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
210         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
211         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
212         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
213
214         // balancing
215         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
216
217         // A                                        B
218         // update_fee                            ->
219         // send (1) commitment_signed            -.
220         //                                       <- update_add_htlc/commitment_signed
221         // send (2) RAA (awaiting remote revoke) -.
222         // (1) commitment_signed is delivered    ->
223         //                                       .- send (3) RAA (awaiting remote revoke)
224         // (2) RAA is delivered                  ->
225         //                                       .- send (4) commitment_signed
226         //                                       <- (3) RAA is delivered
227         // send (5) commitment_signed            -.
228         //                                       <- (4) commitment_signed is delivered
229         // send (6) RAA                          -.
230         // (5) commitment_signed is delivered    ->
231         //                                       <- RAA
232         // (6) RAA is delivered                  ->
233
234         // First nodes[0] generates an update_fee
235         {
236                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
237                 *feerate_lock += 20;
238         }
239         nodes[0].node.timer_tick_occurred();
240         check_added_monitors!(nodes[0], 1);
241
242         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
243         assert_eq!(events_0.len(), 1);
244         let (update_msg, commitment_signed) = match events_0[0] { // (1)
245                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
246                         (update_fee.as_ref(), commitment_signed)
247                 },
248                 _ => panic!("Unexpected event"),
249         };
250
251         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
252
253         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
254         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
255         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
256         check_added_monitors!(nodes[1], 1);
257
258         let payment_event = {
259                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
260                 assert_eq!(events_1.len(), 1);
261                 SendEvent::from_event(events_1.remove(0))
262         };
263         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
264         assert_eq!(payment_event.msgs.len(), 1);
265
266         // ...now when the messages get delivered everyone should be happy
267         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
268         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
269         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
270         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
271         check_added_monitors!(nodes[0], 1);
272
273         // deliver(1), generate (3):
274         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
275         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
276         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
277         check_added_monitors!(nodes[1], 1);
278
279         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
280         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
281         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
282         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
283         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
284         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
285         assert!(bs_update.update_fee.is_none()); // (4)
286         check_added_monitors!(nodes[1], 1);
287
288         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
289         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
290         assert!(as_update.update_add_htlcs.is_empty()); // (5)
291         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
292         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
293         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
294         assert!(as_update.update_fee.is_none()); // (5)
295         check_added_monitors!(nodes[0], 1);
296
297         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
298         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
299         // only (6) so get_event_msg's assert(len == 1) passes
300         check_added_monitors!(nodes[0], 1);
301
302         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
303         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
304         check_added_monitors!(nodes[1], 1);
305
306         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
307         check_added_monitors!(nodes[0], 1);
308
309         let events_2 = nodes[0].node.get_and_clear_pending_events();
310         assert_eq!(events_2.len(), 1);
311         match events_2[0] {
312                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
313                 _ => panic!("Unexpected event"),
314         }
315
316         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
317         check_added_monitors!(nodes[1], 1);
318 }
319
320 #[test]
321 fn test_update_fee_unordered_raa() {
322         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
323         // crash in an earlier version of the update_fee patch)
324         let chanmon_cfgs = create_chanmon_cfgs(2);
325         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
326         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
327         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
328         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
329
330         // balancing
331         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
332
333         // First nodes[0] generates an update_fee
334         {
335                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
336                 *feerate_lock += 20;
337         }
338         nodes[0].node.timer_tick_occurred();
339         check_added_monitors!(nodes[0], 1);
340
341         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
342         assert_eq!(events_0.len(), 1);
343         let update_msg = match events_0[0] { // (1)
344                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
345                         update_fee.as_ref()
346                 },
347                 _ => panic!("Unexpected event"),
348         };
349
350         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
351
352         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
353         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
354         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
355         check_added_monitors!(nodes[1], 1);
356
357         let payment_event = {
358                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
359                 assert_eq!(events_1.len(), 1);
360                 SendEvent::from_event(events_1.remove(0))
361         };
362         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
363         assert_eq!(payment_event.msgs.len(), 1);
364
365         // ...now when the messages get delivered everyone should be happy
366         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
367         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
368         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
369         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
370         check_added_monitors!(nodes[0], 1);
371
372         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
373         check_added_monitors!(nodes[1], 1);
374
375         // We can't continue, sadly, because our (1) now has a bogus signature
376 }
377
378 #[test]
379 fn test_multi_flight_update_fee() {
380         let chanmon_cfgs = create_chanmon_cfgs(2);
381         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
382         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
383         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
384         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
385
386         // A                                        B
387         // update_fee/commitment_signed          ->
388         //                                       .- send (1) RAA and (2) commitment_signed
389         // update_fee (never committed)          ->
390         // (3) update_fee                        ->
391         // We have to manually generate the above update_fee, it is allowed by the protocol but we
392         // don't track which updates correspond to which revoke_and_ack responses so we're in
393         // AwaitingRAA mode and will not generate the update_fee yet.
394         //                                       <- (1) RAA delivered
395         // (3) is generated and send (4) CS      -.
396         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
397         // know the per_commitment_point to use for it.
398         //                                       <- (2) commitment_signed delivered
399         // revoke_and_ack                        ->
400         //                                          B should send no response here
401         // (4) commitment_signed delivered       ->
402         //                                       <- RAA/commitment_signed delivered
403         // revoke_and_ack                        ->
404
405         // First nodes[0] generates an update_fee
406         let initial_feerate;
407         {
408                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
409                 initial_feerate = *feerate_lock;
410                 *feerate_lock = initial_feerate + 20;
411         }
412         nodes[0].node.timer_tick_occurred();
413         check_added_monitors!(nodes[0], 1);
414
415         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
416         assert_eq!(events_0.len(), 1);
417         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
418                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
419                         (update_fee.as_ref().unwrap(), commitment_signed)
420                 },
421                 _ => panic!("Unexpected event"),
422         };
423
424         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
425         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
426         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
427         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
428         check_added_monitors!(nodes[1], 1);
429
430         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
431         // transaction:
432         {
433                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
434                 *feerate_lock = initial_feerate + 40;
435         }
436         nodes[0].node.timer_tick_occurred();
437         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
438         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
439
440         // Create the (3) update_fee message that nodes[0] will generate before it does...
441         let mut update_msg_2 = msgs::UpdateFee {
442                 channel_id: update_msg_1.channel_id.clone(),
443                 feerate_per_kw: (initial_feerate + 30) as u32,
444         };
445
446         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
447
448         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
449         // Deliver (3)
450         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
451
452         // Deliver (1), generating (3) and (4)
453         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
454         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
455         check_added_monitors!(nodes[0], 1);
456         assert!(as_second_update.update_add_htlcs.is_empty());
457         assert!(as_second_update.update_fulfill_htlcs.is_empty());
458         assert!(as_second_update.update_fail_htlcs.is_empty());
459         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
460         // Check that the update_fee newly generated matches what we delivered:
461         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
462         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
463
464         // Deliver (2) commitment_signed
465         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
466         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
467         check_added_monitors!(nodes[0], 1);
468         // No commitment_signed so get_event_msg's assert(len == 1) passes
469
470         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
471         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
472         check_added_monitors!(nodes[1], 1);
473
474         // Delever (4)
475         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
476         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
477         check_added_monitors!(nodes[1], 1);
478
479         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
480         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
481         check_added_monitors!(nodes[0], 1);
482
483         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
484         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
485         // No commitment_signed so get_event_msg's assert(len == 1) passes
486         check_added_monitors!(nodes[0], 1);
487
488         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
489         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
490         check_added_monitors!(nodes[1], 1);
491 }
492
493 fn do_test_sanity_on_in_flight_opens(steps: u8) {
494         // Previously, we had issues deserializing channels when we hadn't connected the first block
495         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
496         // serialization round-trips and simply do steps towards opening a channel and then drop the
497         // Node objects.
498
499         let chanmon_cfgs = create_chanmon_cfgs(2);
500         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
501         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
502         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
503
504         if steps & 0b1000_0000 != 0{
505                 let block = Block {
506                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
507                         txdata: vec![],
508                 };
509                 connect_block(&nodes[0], &block);
510                 connect_block(&nodes[1], &block);
511         }
512
513         if steps & 0x0f == 0 { return; }
514         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
515         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
516
517         if steps & 0x0f == 1 { return; }
518         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
519         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
520
521         if steps & 0x0f == 2 { return; }
522         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
523
524         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
525
526         if steps & 0x0f == 3 { return; }
527         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
528         check_added_monitors!(nodes[0], 0);
529         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
530
531         if steps & 0x0f == 4 { return; }
532         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
533         {
534                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
535                 assert_eq!(added_monitors.len(), 1);
536                 assert_eq!(added_monitors[0].0, funding_output);
537                 added_monitors.clear();
538         }
539         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
540
541         if steps & 0x0f == 5 { return; }
542         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
543         {
544                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
545                 assert_eq!(added_monitors.len(), 1);
546                 assert_eq!(added_monitors[0].0, funding_output);
547                 added_monitors.clear();
548         }
549
550         let events_4 = nodes[0].node.get_and_clear_pending_events();
551         assert_eq!(events_4.len(), 0);
552
553         if steps & 0x0f == 6 { return; }
554         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
555
556         if steps & 0x0f == 7 { return; }
557         confirm_transaction_at(&nodes[0], &tx, 2);
558         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
559         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
560 }
561
562 #[test]
563 fn test_sanity_on_in_flight_opens() {
564         do_test_sanity_on_in_flight_opens(0);
565         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
566         do_test_sanity_on_in_flight_opens(1);
567         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
568         do_test_sanity_on_in_flight_opens(2);
569         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
570         do_test_sanity_on_in_flight_opens(3);
571         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
572         do_test_sanity_on_in_flight_opens(4);
573         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
574         do_test_sanity_on_in_flight_opens(5);
575         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
576         do_test_sanity_on_in_flight_opens(6);
577         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
578         do_test_sanity_on_in_flight_opens(7);
579         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
580         do_test_sanity_on_in_flight_opens(8);
581         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
582 }
583
584 #[test]
585 fn test_update_fee_vanilla() {
586         let chanmon_cfgs = create_chanmon_cfgs(2);
587         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
588         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
589         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
590         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
591
592         {
593                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
594                 *feerate_lock += 25;
595         }
596         nodes[0].node.timer_tick_occurred();
597         check_added_monitors!(nodes[0], 1);
598
599         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
600         assert_eq!(events_0.len(), 1);
601         let (update_msg, commitment_signed) = match events_0[0] {
602                         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 } } => {
603                         (update_fee.as_ref(), commitment_signed)
604                 },
605                 _ => panic!("Unexpected event"),
606         };
607         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
608
609         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
610         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
611         check_added_monitors!(nodes[1], 1);
612
613         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
614         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
615         check_added_monitors!(nodes[0], 1);
616
617         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
618         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
619         // No commitment_signed so get_event_msg's assert(len == 1) passes
620         check_added_monitors!(nodes[0], 1);
621
622         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
623         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
624         check_added_monitors!(nodes[1], 1);
625 }
626
627 #[test]
628 fn test_update_fee_that_funder_cannot_afford() {
629         let chanmon_cfgs = create_chanmon_cfgs(2);
630         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
631         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
632         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
633         let channel_value = 5000;
634         let push_sats = 700;
635         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
636         let channel_id = chan.2;
637         let secp_ctx = Secp256k1::new();
638         let default_config = UserConfig::default();
639         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
640
641         let opt_anchors = false;
642
643         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
644         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
645         // calculate two different feerates here - the expected local limit as well as the expected
646         // remote limit.
647         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;
648         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
649         {
650                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
651                 *feerate_lock = feerate;
652         }
653         nodes[0].node.timer_tick_occurred();
654         check_added_monitors!(nodes[0], 1);
655         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
656
657         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
658
659         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
660
661         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
662         {
663                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
664
665                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
666                 assert_eq!(commitment_tx.output.len(), 2);
667                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
668                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
669                 actual_fee = channel_value - actual_fee;
670                 assert_eq!(total_fee, actual_fee);
671         }
672
673         {
674                 // Increment the feerate by a small constant, accounting for rounding errors
675                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
676                 *feerate_lock += 4;
677         }
678         nodes[0].node.timer_tick_occurred();
679         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
680         check_added_monitors!(nodes[0], 0);
681
682         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
683
684         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
685         // needed to sign the new commitment tx and (2) sign the new commitment tx.
686         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
687                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
688                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
689                 let chan_signer = local_chan.get_signer();
690                 let pubkeys = chan_signer.pubkeys();
691                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
692                  pubkeys.funding_pubkey)
693         };
694         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
695                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
696                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
697                 let chan_signer = remote_chan.get_signer();
698                 let pubkeys = chan_signer.pubkeys();
699                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
700                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
701                  pubkeys.funding_pubkey)
702         };
703
704         // Assemble the set of keys we can use for signatures for our commitment_signed message.
705         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
706                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
707
708         let res = {
709                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
710                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
711                 let local_chan_signer = local_chan.get_signer();
712                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
713                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
714                         INITIAL_COMMITMENT_NUMBER - 1,
715                         push_sats,
716                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
717                         opt_anchors, local_funding, remote_funding,
718                         commit_tx_keys.clone(),
719                         non_buffer_feerate + 4,
720                         &mut htlcs,
721                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
722                 );
723                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
724         };
725
726         let commit_signed_msg = msgs::CommitmentSigned {
727                 channel_id: chan.2,
728                 signature: res.0,
729                 htlc_signatures: res.1
730         };
731
732         let update_fee = msgs::UpdateFee {
733                 channel_id: chan.2,
734                 feerate_per_kw: non_buffer_feerate + 4,
735         };
736
737         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
738
739         //While producing the commitment_signed response after handling a received update_fee request the
740         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
741         //Should produce and error.
742         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
743         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
744         check_added_monitors!(nodes[1], 1);
745         check_closed_broadcast!(nodes[1], true);
746         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
747 }
748
749 #[test]
750 fn test_update_fee_with_fundee_update_add_htlc() {
751         let chanmon_cfgs = create_chanmon_cfgs(2);
752         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
753         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
754         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
755         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
756
757         // balancing
758         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
759
760         {
761                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
762                 *feerate_lock += 20;
763         }
764         nodes[0].node.timer_tick_occurred();
765         check_added_monitors!(nodes[0], 1);
766
767         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
768         assert_eq!(events_0.len(), 1);
769         let (update_msg, commitment_signed) = match events_0[0] {
770                         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 } } => {
771                         (update_fee.as_ref(), commitment_signed)
772                 },
773                 _ => panic!("Unexpected event"),
774         };
775         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
776         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
777         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
778         check_added_monitors!(nodes[1], 1);
779
780         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
781
782         // nothing happens since node[1] is in AwaitingRemoteRevoke
783         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
784         {
785                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
786                 assert_eq!(added_monitors.len(), 0);
787                 added_monitors.clear();
788         }
789         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
790         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
791         // node[1] has nothing to do
792
793         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
794         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
795         check_added_monitors!(nodes[0], 1);
796
797         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
798         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
799         // No commitment_signed so get_event_msg's assert(len == 1) passes
800         check_added_monitors!(nodes[0], 1);
801         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
802         check_added_monitors!(nodes[1], 1);
803         // AwaitingRemoteRevoke ends here
804
805         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
806         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
807         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
808         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
809         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
810         assert_eq!(commitment_update.update_fee.is_none(), true);
811
812         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
813         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
814         check_added_monitors!(nodes[0], 1);
815         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
816
817         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
818         check_added_monitors!(nodes[1], 1);
819         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
820
821         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
822         check_added_monitors!(nodes[1], 1);
823         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
824         // No commitment_signed so get_event_msg's assert(len == 1) passes
825
826         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
827         check_added_monitors!(nodes[0], 1);
828         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
829
830         expect_pending_htlcs_forwardable!(nodes[0]);
831
832         let events = nodes[0].node.get_and_clear_pending_events();
833         assert_eq!(events.len(), 1);
834         match events[0] {
835                 Event::PaymentReceived { .. } => { },
836                 _ => panic!("Unexpected event"),
837         };
838
839         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
840
841         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
842         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
843         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
844         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
845         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
846 }
847
848 #[test]
849 fn test_update_fee() {
850         let chanmon_cfgs = create_chanmon_cfgs(2);
851         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
852         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
853         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
854         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
855         let channel_id = chan.2;
856
857         // A                                        B
858         // (1) update_fee/commitment_signed      ->
859         //                                       <- (2) revoke_and_ack
860         //                                       .- send (3) commitment_signed
861         // (4) update_fee/commitment_signed      ->
862         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
863         //                                       <- (3) commitment_signed delivered
864         // send (6) revoke_and_ack               -.
865         //                                       <- (5) deliver revoke_and_ack
866         // (6) deliver revoke_and_ack            ->
867         //                                       .- send (7) commitment_signed in response to (4)
868         //                                       <- (7) deliver commitment_signed
869         // revoke_and_ack                        ->
870
871         // Create and deliver (1)...
872         let feerate;
873         {
874                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
875                 feerate = *feerate_lock;
876                 *feerate_lock = feerate + 20;
877         }
878         nodes[0].node.timer_tick_occurred();
879         check_added_monitors!(nodes[0], 1);
880
881         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
882         assert_eq!(events_0.len(), 1);
883         let (update_msg, commitment_signed) = match events_0[0] {
884                         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 } } => {
885                         (update_fee.as_ref(), commitment_signed)
886                 },
887                 _ => panic!("Unexpected event"),
888         };
889         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
890
891         // Generate (2) and (3):
892         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
893         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
894         check_added_monitors!(nodes[1], 1);
895
896         // Deliver (2):
897         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
898         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
899         check_added_monitors!(nodes[0], 1);
900
901         // Create and deliver (4)...
902         {
903                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
904                 *feerate_lock = feerate + 30;
905         }
906         nodes[0].node.timer_tick_occurred();
907         check_added_monitors!(nodes[0], 1);
908         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
909         assert_eq!(events_0.len(), 1);
910         let (update_msg, commitment_signed) = match events_0[0] {
911                         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 } } => {
912                         (update_fee.as_ref(), commitment_signed)
913                 },
914                 _ => panic!("Unexpected event"),
915         };
916
917         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
918         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
919         check_added_monitors!(nodes[1], 1);
920         // ... creating (5)
921         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
922         // No commitment_signed so get_event_msg's assert(len == 1) passes
923
924         // Handle (3), creating (6):
925         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
926         check_added_monitors!(nodes[0], 1);
927         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
928         // No commitment_signed so get_event_msg's assert(len == 1) passes
929
930         // Deliver (5):
931         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
932         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
933         check_added_monitors!(nodes[0], 1);
934
935         // Deliver (6), creating (7):
936         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
937         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
938         assert!(commitment_update.update_add_htlcs.is_empty());
939         assert!(commitment_update.update_fulfill_htlcs.is_empty());
940         assert!(commitment_update.update_fail_htlcs.is_empty());
941         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
942         assert!(commitment_update.update_fee.is_none());
943         check_added_monitors!(nodes[1], 1);
944
945         // Deliver (7)
946         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
947         check_added_monitors!(nodes[0], 1);
948         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
949         // No commitment_signed so get_event_msg's assert(len == 1) passes
950
951         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
952         check_added_monitors!(nodes[1], 1);
953         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
954
955         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
956         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
957         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
958         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
959         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
960 }
961
962 #[test]
963 fn fake_network_test() {
964         // Simple test which builds a network of ChannelManagers, connects them to each other, and
965         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
966         let chanmon_cfgs = create_chanmon_cfgs(4);
967         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
968         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
969         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
970
971         // Create some initial channels
972         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
973         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
974         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
975
976         // Rebalance the network a bit by relaying one payment through all the channels...
977         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
978         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
979         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
980         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
981
982         // Send some more payments
983         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
984         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
985         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
986
987         // Test failure packets
988         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
989         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
990
991         // Add a new channel that skips 3
992         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
993
994         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
995         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
996         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
997         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
998         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
999         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1000         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1001
1002         // Do some rebalance loop payments, simultaneously
1003         let mut hops = Vec::with_capacity(3);
1004         hops.push(RouteHop {
1005                 pubkey: nodes[2].node.get_our_node_id(),
1006                 node_features: NodeFeatures::empty(),
1007                 short_channel_id: chan_2.0.contents.short_channel_id,
1008                 channel_features: ChannelFeatures::empty(),
1009                 fee_msat: 0,
1010                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1011         });
1012         hops.push(RouteHop {
1013                 pubkey: nodes[3].node.get_our_node_id(),
1014                 node_features: NodeFeatures::empty(),
1015                 short_channel_id: chan_3.0.contents.short_channel_id,
1016                 channel_features: ChannelFeatures::empty(),
1017                 fee_msat: 0,
1018                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1019         });
1020         hops.push(RouteHop {
1021                 pubkey: nodes[1].node.get_our_node_id(),
1022                 node_features: NodeFeatures::known(),
1023                 short_channel_id: chan_4.0.contents.short_channel_id,
1024                 channel_features: ChannelFeatures::known(),
1025                 fee_msat: 1000000,
1026                 cltv_expiry_delta: TEST_FINAL_CLTV,
1027         });
1028         hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1029         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;
1030         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;
1031
1032         let mut hops = Vec::with_capacity(3);
1033         hops.push(RouteHop {
1034                 pubkey: nodes[3].node.get_our_node_id(),
1035                 node_features: NodeFeatures::empty(),
1036                 short_channel_id: chan_4.0.contents.short_channel_id,
1037                 channel_features: ChannelFeatures::empty(),
1038                 fee_msat: 0,
1039                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1040         });
1041         hops.push(RouteHop {
1042                 pubkey: nodes[2].node.get_our_node_id(),
1043                 node_features: NodeFeatures::empty(),
1044                 short_channel_id: chan_3.0.contents.short_channel_id,
1045                 channel_features: ChannelFeatures::empty(),
1046                 fee_msat: 0,
1047                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1048         });
1049         hops.push(RouteHop {
1050                 pubkey: nodes[1].node.get_our_node_id(),
1051                 node_features: NodeFeatures::known(),
1052                 short_channel_id: chan_2.0.contents.short_channel_id,
1053                 channel_features: ChannelFeatures::known(),
1054                 fee_msat: 1000000,
1055                 cltv_expiry_delta: TEST_FINAL_CLTV,
1056         });
1057         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;
1058         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;
1059         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;
1060
1061         // Claim the rebalances...
1062         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1063         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1064
1065         // Close down the channels...
1066         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1067         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1068         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1069         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1070         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1071         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1072         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1073         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1074         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1075         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1076         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1077         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1078 }
1079
1080 #[test]
1081 fn holding_cell_htlc_counting() {
1082         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1083         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1084         // commitment dance rounds.
1085         let chanmon_cfgs = create_chanmon_cfgs(3);
1086         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1087         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1088         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1089         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1090         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1091
1092         let mut payments = Vec::new();
1093         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1094                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1095                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1096                 payments.push((payment_preimage, payment_hash));
1097         }
1098         check_added_monitors!(nodes[1], 1);
1099
1100         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1101         assert_eq!(events.len(), 1);
1102         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1103         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1104
1105         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1106         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1107         // another HTLC.
1108         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1109         {
1110                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1111                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1112                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1113                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1114         }
1115
1116         // This should also be true if we try to forward a payment.
1117         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1118         {
1119                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1120                 check_added_monitors!(nodes[0], 1);
1121         }
1122
1123         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1124         assert_eq!(events.len(), 1);
1125         let payment_event = SendEvent::from_event(events.pop().unwrap());
1126         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1127
1128         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1129         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1130         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1131         // fails), the second will process the resulting failure and fail the HTLC backward.
1132         expect_pending_htlcs_forwardable!(nodes[1]);
1133         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1134         check_added_monitors!(nodes[1], 1);
1135
1136         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1137         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1138         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1139
1140         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1141
1142         // Now forward all the pending HTLCs and claim them back
1143         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1144         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1145         check_added_monitors!(nodes[2], 1);
1146
1147         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1148         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1149         check_added_monitors!(nodes[1], 1);
1150         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1151
1152         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1153         check_added_monitors!(nodes[1], 1);
1154         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1155
1156         for ref update in as_updates.update_add_htlcs.iter() {
1157                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1158         }
1159         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1160         check_added_monitors!(nodes[2], 1);
1161         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1162         check_added_monitors!(nodes[2], 1);
1163         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1164
1165         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1166         check_added_monitors!(nodes[1], 1);
1167         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1168         check_added_monitors!(nodes[1], 1);
1169         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1170
1171         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1172         check_added_monitors!(nodes[2], 1);
1173
1174         expect_pending_htlcs_forwardable!(nodes[2]);
1175
1176         let events = nodes[2].node.get_and_clear_pending_events();
1177         assert_eq!(events.len(), payments.len());
1178         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1179                 match event {
1180                         &Event::PaymentReceived { ref payment_hash, .. } => {
1181                                 assert_eq!(*payment_hash, *hash);
1182                         },
1183                         _ => panic!("Unexpected event"),
1184                 };
1185         }
1186
1187         for (preimage, _) in payments.drain(..) {
1188                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1189         }
1190
1191         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1192 }
1193
1194 #[test]
1195 fn duplicate_htlc_test() {
1196         // Test that we accept duplicate payment_hash HTLCs across the network and that
1197         // claiming/failing them are all separate and don't affect each other
1198         let chanmon_cfgs = create_chanmon_cfgs(6);
1199         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1200         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1201         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1202
1203         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1204         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1205         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1206         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1207         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1208         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1209
1210         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1211
1212         *nodes[0].network_payment_count.borrow_mut() -= 1;
1213         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1214
1215         *nodes[0].network_payment_count.borrow_mut() -= 1;
1216         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1217
1218         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1219         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1220         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1221 }
1222
1223 #[test]
1224 fn test_duplicate_htlc_different_direction_onchain() {
1225         // Test that ChannelMonitor doesn't generate 2 preimage txn
1226         // when we have 2 HTLCs with same preimage that go across a node
1227         // in opposite directions, even with the same payment secret.
1228         let chanmon_cfgs = create_chanmon_cfgs(2);
1229         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1230         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1231         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1232
1233         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1234
1235         // balancing
1236         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1237
1238         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1239
1240         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1241         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1242         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1243
1244         // Provide preimage to node 0 by claiming payment
1245         nodes[0].node.claim_funds(payment_preimage);
1246         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1247         check_added_monitors!(nodes[0], 1);
1248
1249         // Broadcast node 1 commitment txn
1250         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1251
1252         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1253         let mut has_both_htlcs = 0; // check htlcs match ones committed
1254         for outp in remote_txn[0].output.iter() {
1255                 if outp.value == 800_000 / 1000 {
1256                         has_both_htlcs += 1;
1257                 } else if outp.value == 900_000 / 1000 {
1258                         has_both_htlcs += 1;
1259                 }
1260         }
1261         assert_eq!(has_both_htlcs, 2);
1262
1263         mine_transaction(&nodes[0], &remote_txn[0]);
1264         check_added_monitors!(nodes[0], 1);
1265         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1266         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1267
1268         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1269         assert_eq!(claim_txn.len(), 8);
1270
1271         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1272
1273         check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1274         check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1275
1276         let bump_tx = if claim_txn[1] == claim_txn[4] {
1277                 assert_eq!(claim_txn[1], claim_txn[4]);
1278                 assert_eq!(claim_txn[2], claim_txn[5]);
1279
1280                 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1281
1282                 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1283                 &claim_txn[3]
1284         } else {
1285                 assert_eq!(claim_txn[1], claim_txn[3]);
1286                 assert_eq!(claim_txn[2], claim_txn[4]);
1287
1288                 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1289
1290                 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1291
1292                 &claim_txn[7]
1293         };
1294
1295         assert_eq!(claim_txn[0].input.len(), 1);
1296         assert_eq!(bump_tx.input.len(), 1);
1297         assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1298
1299         assert_eq!(claim_txn[0].input.len(), 1);
1300         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1301         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1302
1303         assert_eq!(claim_txn[6].input.len(), 1);
1304         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1305         check_spends!(claim_txn[6], remote_txn[0]);
1306         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1307
1308         let events = nodes[0].node.get_and_clear_pending_msg_events();
1309         assert_eq!(events.len(), 3);
1310         for e in events {
1311                 match e {
1312                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1313                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1314                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1315                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1316                         },
1317                         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, .. } } => {
1318                                 assert!(update_add_htlcs.is_empty());
1319                                 assert!(update_fail_htlcs.is_empty());
1320                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1321                                 assert!(update_fail_malformed_htlcs.is_empty());
1322                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1323                         },
1324                         _ => panic!("Unexpected event"),
1325                 }
1326         }
1327 }
1328
1329 #[test]
1330 fn test_basic_channel_reserve() {
1331         let chanmon_cfgs = create_chanmon_cfgs(2);
1332         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1333         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1334         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1335         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1336
1337         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1338         let channel_reserve = chan_stat.channel_reserve_msat;
1339
1340         // The 2* and +1 are for the fee spike reserve.
1341         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1342         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1343         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1344         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1345         match err {
1346                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1347                         match &fails[0] {
1348                                 &APIError::ChannelUnavailable{ref err} =>
1349                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1350                                 _ => panic!("Unexpected error variant"),
1351                         }
1352                 },
1353                 _ => panic!("Unexpected error variant"),
1354         }
1355         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1356         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);
1357
1358         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1359 }
1360
1361 #[test]
1362 fn test_fee_spike_violation_fails_htlc() {
1363         let chanmon_cfgs = create_chanmon_cfgs(2);
1364         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1365         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1366         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1367         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1368
1369         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1370         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1371         let secp_ctx = Secp256k1::new();
1372         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1373
1374         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1375
1376         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1377         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1378         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1379         let msg = msgs::UpdateAddHTLC {
1380                 channel_id: chan.2,
1381                 htlc_id: 0,
1382                 amount_msat: htlc_msat,
1383                 payment_hash: payment_hash,
1384                 cltv_expiry: htlc_cltv,
1385                 onion_routing_packet: onion_packet,
1386         };
1387
1388         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1389
1390         // Now manually create the commitment_signed message corresponding to the update_add
1391         // nodes[0] just sent. In the code for construction of this message, "local" refers
1392         // to the sender of the message, and "remote" refers to the receiver.
1393
1394         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1395
1396         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1397
1398         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1399         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1400         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1401                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1402                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1403                 let chan_signer = local_chan.get_signer();
1404                 // Make the signer believe we validated another commitment, so we can release the secret
1405                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1406
1407                 let pubkeys = chan_signer.pubkeys();
1408                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1409                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1410                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1411                  chan_signer.pubkeys().funding_pubkey)
1412         };
1413         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1414                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1415                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1416                 let chan_signer = remote_chan.get_signer();
1417                 let pubkeys = chan_signer.pubkeys();
1418                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1419                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1420                  chan_signer.pubkeys().funding_pubkey)
1421         };
1422
1423         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1424         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1425                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1426
1427         // Build the remote commitment transaction so we can sign it, and then later use the
1428         // signature for the commitment_signed message.
1429         let local_chan_balance = 1313;
1430
1431         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1432                 offered: false,
1433                 amount_msat: 3460001,
1434                 cltv_expiry: htlc_cltv,
1435                 payment_hash,
1436                 transaction_output_index: Some(1),
1437         };
1438
1439         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1440
1441         let res = {
1442                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1443                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1444                 let local_chan_signer = local_chan.get_signer();
1445                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1446                         commitment_number,
1447                         95000,
1448                         local_chan_balance,
1449                         local_chan.opt_anchors(), local_funding, remote_funding,
1450                         commit_tx_keys.clone(),
1451                         feerate_per_kw,
1452                         &mut vec![(accepted_htlc_info, ())],
1453                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1454                 );
1455                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1456         };
1457
1458         let commit_signed_msg = msgs::CommitmentSigned {
1459                 channel_id: chan.2,
1460                 signature: res.0,
1461                 htlc_signatures: res.1
1462         };
1463
1464         // Send the commitment_signed message to the nodes[1].
1465         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1466         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1467
1468         // Send the RAA to nodes[1].
1469         let raa_msg = msgs::RevokeAndACK {
1470                 channel_id: chan.2,
1471                 per_commitment_secret: local_secret,
1472                 next_per_commitment_point: next_local_point
1473         };
1474         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1475
1476         let events = nodes[1].node.get_and_clear_pending_msg_events();
1477         assert_eq!(events.len(), 1);
1478         // Make sure the HTLC failed in the way we expect.
1479         match events[0] {
1480                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1481                         assert_eq!(update_fail_htlcs.len(), 1);
1482                         update_fail_htlcs[0].clone()
1483                 },
1484                 _ => panic!("Unexpected event"),
1485         };
1486         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1487                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1488
1489         check_added_monitors!(nodes[1], 2);
1490 }
1491
1492 #[test]
1493 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1494         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1495         // Set the fee rate for the channel very high, to the point where the fundee
1496         // sending any above-dust amount would result in a channel reserve violation.
1497         // In this test we check that we would be prevented from sending an HTLC in
1498         // this situation.
1499         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1500         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1501         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1502         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1503         let default_config = UserConfig::default();
1504         let opt_anchors = false;
1505
1506         let mut push_amt = 100_000_000;
1507         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1508
1509         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1510
1511         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1512
1513         // Sending exactly enough to hit the reserve amount should be accepted
1514         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1515                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1516         }
1517
1518         // However one more HTLC should be significantly over the reserve amount and fail.
1519         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1520         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1521                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1522         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1523         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);
1524 }
1525
1526 #[test]
1527 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1528         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1529         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1530         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1531         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1532         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1533         let default_config = UserConfig::default();
1534         let opt_anchors = false;
1535
1536         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1537         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1538         // transaction fee with 0 HTLCs (183 sats)).
1539         let mut push_amt = 100_000_000;
1540         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1541         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1542         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1543
1544         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1545         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1546                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1547         }
1548
1549         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1550         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1551         let secp_ctx = Secp256k1::new();
1552         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1553         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1554         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1555         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1556         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1557         let msg = msgs::UpdateAddHTLC {
1558                 channel_id: chan.2,
1559                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1560                 amount_msat: htlc_msat,
1561                 payment_hash: payment_hash,
1562                 cltv_expiry: htlc_cltv,
1563                 onion_routing_packet: onion_packet,
1564         };
1565
1566         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1567         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1568         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);
1569         assert_eq!(nodes[0].node.list_channels().len(), 0);
1570         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1571         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1572         check_added_monitors!(nodes[0], 1);
1573         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() });
1574 }
1575
1576 #[test]
1577 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1578         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1579         // calculating our commitment transaction fee (this was previously broken).
1580         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1581         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1582
1583         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1584         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1585         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1586         let default_config = UserConfig::default();
1587         let opt_anchors = false;
1588
1589         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1590         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1591         // transaction fee with 0 HTLCs (183 sats)).
1592         let mut push_amt = 100_000_000;
1593         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1594         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1595         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1596
1597         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1598                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1599         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1600         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1601         // commitment transaction fee.
1602         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1603
1604         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1605         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1606                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1607         }
1608
1609         // One more than the dust amt should fail, however.
1610         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1611         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1612                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1613 }
1614
1615 #[test]
1616 fn test_chan_init_feerate_unaffordability() {
1617         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1618         // channel reserve and feerate requirements.
1619         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1620         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1621         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1622         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1623         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1624         let default_config = UserConfig::default();
1625         let opt_anchors = false;
1626
1627         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1628         // HTLC.
1629         let mut push_amt = 100_000_000;
1630         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1631         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1632                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1633
1634         // During open, we don't have a "counterparty channel reserve" to check against, so that
1635         // requirement only comes into play on the open_channel handling side.
1636         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1637         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1638         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1639         open_channel_msg.push_msat += 1;
1640         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1641
1642         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1643         assert_eq!(msg_events.len(), 1);
1644         match msg_events[0] {
1645                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1646                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1647                 },
1648                 _ => panic!("Unexpected event"),
1649         }
1650 }
1651
1652 #[test]
1653 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1654         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1655         // calculating our counterparty's commitment transaction fee (this was previously broken).
1656         let chanmon_cfgs = create_chanmon_cfgs(2);
1657         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1658         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1659         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1660         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1661
1662         let payment_amt = 46000; // Dust amount
1663         // In the previous code, these first four payments would succeed.
1664         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1665         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1666         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1667         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1668
1669         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1670         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1671         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1672         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1673         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1674         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1675
1676         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1677         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1678         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1679         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1680 }
1681
1682 #[test]
1683 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1684         let chanmon_cfgs = create_chanmon_cfgs(3);
1685         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1686         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1687         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1688         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1689         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1690
1691         let feemsat = 239;
1692         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1693         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1694         let feerate = get_feerate!(nodes[0], chan.2);
1695         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1696
1697         // Add a 2* and +1 for the fee spike reserve.
1698         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1699         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;
1700         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1701
1702         // Add a pending HTLC.
1703         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1704         let payment_event_1 = {
1705                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1706                 check_added_monitors!(nodes[0], 1);
1707
1708                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1709                 assert_eq!(events.len(), 1);
1710                 SendEvent::from_event(events.remove(0))
1711         };
1712         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1713
1714         // Attempt to trigger a channel reserve violation --> payment failure.
1715         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1716         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;
1717         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1718         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1719
1720         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1721         let secp_ctx = Secp256k1::new();
1722         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1723         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1724         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1725         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1726         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1727         let msg = msgs::UpdateAddHTLC {
1728                 channel_id: chan.2,
1729                 htlc_id: 1,
1730                 amount_msat: htlc_msat + 1,
1731                 payment_hash: our_payment_hash_1,
1732                 cltv_expiry: htlc_cltv,
1733                 onion_routing_packet: onion_packet,
1734         };
1735
1736         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1737         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1738         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1739         assert_eq!(nodes[1].node.list_channels().len(), 1);
1740         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1741         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1742         check_added_monitors!(nodes[1], 1);
1743         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1744 }
1745
1746 #[test]
1747 fn test_inbound_outbound_capacity_is_not_zero() {
1748         let chanmon_cfgs = create_chanmon_cfgs(2);
1749         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1750         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1751         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1752         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1753         let channels0 = node_chanmgrs[0].list_channels();
1754         let channels1 = node_chanmgrs[1].list_channels();
1755         let default_config = UserConfig::default();
1756         assert_eq!(channels0.len(), 1);
1757         assert_eq!(channels1.len(), 1);
1758
1759         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1760         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1761         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1762
1763         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1764         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1765 }
1766
1767 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1768         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1769 }
1770
1771 #[test]
1772 fn test_channel_reserve_holding_cell_htlcs() {
1773         let chanmon_cfgs = create_chanmon_cfgs(3);
1774         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1775         // When this test was written, the default base fee floated based on the HTLC count.
1776         // It is now fixed, so we simply set the fee to the expected value here.
1777         let mut config = test_default_channel_config();
1778         config.channel_config.forwarding_fee_base_msat = 239;
1779         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1780         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1781         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1782         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1783
1784         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1785         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1786
1787         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1788         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1789
1790         macro_rules! expect_forward {
1791                 ($node: expr) => {{
1792                         let mut events = $node.node.get_and_clear_pending_msg_events();
1793                         assert_eq!(events.len(), 1);
1794                         check_added_monitors!($node, 1);
1795                         let payment_event = SendEvent::from_event(events.remove(0));
1796                         payment_event
1797                 }}
1798         }
1799
1800         let feemsat = 239; // set above
1801         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1802         let feerate = get_feerate!(nodes[0], chan_1.2);
1803         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1804
1805         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1806
1807         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1808         {
1809                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1810                         .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1811                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0, TEST_FINAL_CLTV);
1812                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1813                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1814
1815                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1816                         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)));
1817                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1818                 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);
1819         }
1820
1821         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1822         // nodes[0]'s wealth
1823         loop {
1824                 let amt_msat = recv_value_0 + total_fee_msat;
1825                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1826                 // Also, ensure that each payment has enough to be over the dust limit to
1827                 // ensure it'll be included in each commit tx fee calculation.
1828                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1829                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1830                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1831                         break;
1832                 }
1833
1834                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1835                         .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1836                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1837                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1838                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1839
1840                 let (stat01_, stat11_, stat12_, stat22_) = (
1841                         get_channel_value_stat!(nodes[0], chan_1.2),
1842                         get_channel_value_stat!(nodes[1], chan_1.2),
1843                         get_channel_value_stat!(nodes[1], chan_2.2),
1844                         get_channel_value_stat!(nodes[2], chan_2.2),
1845                 );
1846
1847                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1848                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1849                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1850                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1851                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1852         }
1853
1854         // adding pending output.
1855         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1856         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1857         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1858         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1859         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1860         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1861         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1862         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1863         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1864         // policy.
1865         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1866         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1867         let amt_msat_1 = recv_value_1 + total_fee_msat;
1868
1869         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);
1870         let payment_event_1 = {
1871                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1872                 check_added_monitors!(nodes[0], 1);
1873
1874                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1875                 assert_eq!(events.len(), 1);
1876                 SendEvent::from_event(events.remove(0))
1877         };
1878         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1879
1880         // channel reserve test with htlc pending output > 0
1881         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1882         {
1883                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1884                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1885                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1886                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1887         }
1888
1889         // split the rest to test holding cell
1890         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1891         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1892         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1893         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1894         {
1895                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1896                 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);
1897         }
1898
1899         // now see if they go through on both sides
1900         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);
1901         // but this will stuck in the holding cell
1902         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1903         check_added_monitors!(nodes[0], 0);
1904         let events = nodes[0].node.get_and_clear_pending_events();
1905         assert_eq!(events.len(), 0);
1906
1907         // test with outbound holding cell amount > 0
1908         {
1909                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1910                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1911                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1912                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1913                 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);
1914         }
1915
1916         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);
1917         // this will also stuck in the holding cell
1918         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1919         check_added_monitors!(nodes[0], 0);
1920         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1921         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1922
1923         // flush the pending htlc
1924         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1925         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1926         check_added_monitors!(nodes[1], 1);
1927
1928         // the pending htlc should be promoted to committed
1929         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1930         check_added_monitors!(nodes[0], 1);
1931         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1932
1933         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1934         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1935         // No commitment_signed so get_event_msg's assert(len == 1) passes
1936         check_added_monitors!(nodes[0], 1);
1937
1938         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1939         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1940         check_added_monitors!(nodes[1], 1);
1941
1942         expect_pending_htlcs_forwardable!(nodes[1]);
1943
1944         let ref payment_event_11 = expect_forward!(nodes[1]);
1945         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1946         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1947
1948         expect_pending_htlcs_forwardable!(nodes[2]);
1949         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1950
1951         // flush the htlcs in the holding cell
1952         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1953         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1954         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1955         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1956         expect_pending_htlcs_forwardable!(nodes[1]);
1957
1958         let ref payment_event_3 = expect_forward!(nodes[1]);
1959         assert_eq!(payment_event_3.msgs.len(), 2);
1960         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1961         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1962
1963         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1964         expect_pending_htlcs_forwardable!(nodes[2]);
1965
1966         let events = nodes[2].node.get_and_clear_pending_events();
1967         assert_eq!(events.len(), 2);
1968         match events[0] {
1969                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1970                         assert_eq!(our_payment_hash_21, *payment_hash);
1971                         assert_eq!(recv_value_21, amount_msat);
1972                         match &purpose {
1973                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1974                                         assert!(payment_preimage.is_none());
1975                                         assert_eq!(our_payment_secret_21, *payment_secret);
1976                                 },
1977                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1978                         }
1979                 },
1980                 _ => panic!("Unexpected event"),
1981         }
1982         match events[1] {
1983                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1984                         assert_eq!(our_payment_hash_22, *payment_hash);
1985                         assert_eq!(recv_value_22, amount_msat);
1986                         match &purpose {
1987                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1988                                         assert!(payment_preimage.is_none());
1989                                         assert_eq!(our_payment_secret_22, *payment_secret);
1990                                 },
1991                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1992                         }
1993                 },
1994                 _ => panic!("Unexpected event"),
1995         }
1996
1997         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1998         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1999         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2000
2001         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2002         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2003         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2004
2005         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2006         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);
2007         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2008         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2009         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2010
2011         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2012         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2013 }
2014
2015 #[test]
2016 fn channel_reserve_in_flight_removes() {
2017         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2018         // can send to its counterparty, but due to update ordering, the other side may not yet have
2019         // considered those HTLCs fully removed.
2020         // This tests that we don't count HTLCs which will not be included in the next remote
2021         // commitment transaction towards the reserve value (as it implies no commitment transaction
2022         // will be generated which violates the remote reserve value).
2023         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2024         // To test this we:
2025         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2026         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2027         //    you only consider the value of the first HTLC, it may not),
2028         //  * start routing a third HTLC from A to B,
2029         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2030         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2031         //  * deliver the first fulfill from B
2032         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2033         //    claim,
2034         //  * deliver A's response CS and RAA.
2035         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2036         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2037         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2038         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2039         let chanmon_cfgs = create_chanmon_cfgs(2);
2040         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2041         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2042         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2043         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2044
2045         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2046         // Route the first two HTLCs.
2047         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2048         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2049         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2050
2051         // Start routing the third HTLC (this is just used to get everyone in the right state).
2052         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2053         let send_1 = {
2054                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2055                 check_added_monitors!(nodes[0], 1);
2056                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2057                 assert_eq!(events.len(), 1);
2058                 SendEvent::from_event(events.remove(0))
2059         };
2060
2061         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2062         // initial fulfill/CS.
2063         nodes[1].node.claim_funds(payment_preimage_1);
2064         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2065         check_added_monitors!(nodes[1], 1);
2066         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2067
2068         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2069         // remove the second HTLC when we send the HTLC back from B to A.
2070         nodes[1].node.claim_funds(payment_preimage_2);
2071         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2072         check_added_monitors!(nodes[1], 1);
2073         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2074
2075         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2076         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2077         check_added_monitors!(nodes[0], 1);
2078         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2079         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2080
2081         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2082         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2083         check_added_monitors!(nodes[1], 1);
2084         // B is already AwaitingRAA, so cant generate a CS here
2085         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2086
2087         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2088         check_added_monitors!(nodes[1], 1);
2089         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2090
2091         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2092         check_added_monitors!(nodes[0], 1);
2093         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2094
2095         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2096         check_added_monitors!(nodes[1], 1);
2097         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2098
2099         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2100         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2101         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2102         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2103         // on-chain as necessary).
2104         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2105         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2106         check_added_monitors!(nodes[0], 1);
2107         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2108         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2109
2110         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2111         check_added_monitors!(nodes[1], 1);
2112         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2113
2114         expect_pending_htlcs_forwardable!(nodes[1]);
2115         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2116
2117         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2118         // resolve the second HTLC from A's point of view.
2119         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2120         check_added_monitors!(nodes[0], 1);
2121         expect_payment_path_successful!(nodes[0]);
2122         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2123
2124         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2125         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2126         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2127         let send_2 = {
2128                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2129                 check_added_monitors!(nodes[1], 1);
2130                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2131                 assert_eq!(events.len(), 1);
2132                 SendEvent::from_event(events.remove(0))
2133         };
2134
2135         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2136         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2137         check_added_monitors!(nodes[0], 1);
2138         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2139
2140         // Now just resolve all the outstanding messages/HTLCs for completeness...
2141
2142         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2143         check_added_monitors!(nodes[1], 1);
2144         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2145
2146         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2147         check_added_monitors!(nodes[1], 1);
2148
2149         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2150         check_added_monitors!(nodes[0], 1);
2151         expect_payment_path_successful!(nodes[0]);
2152         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2153
2154         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2155         check_added_monitors!(nodes[1], 1);
2156         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
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
2161         expect_pending_htlcs_forwardable!(nodes[0]);
2162         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2163
2164         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2165         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2166 }
2167
2168 #[test]
2169 fn channel_monitor_network_test() {
2170         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2171         // tests that ChannelMonitor is able to recover from various states.
2172         let chanmon_cfgs = create_chanmon_cfgs(5);
2173         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2174         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2175         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2176
2177         // Create some initial channels
2178         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2179         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2180         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2181         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2182
2183         // Make sure all nodes are at the same starting height
2184         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2185         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2186         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2187         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2188         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2189
2190         // Rebalance the network a bit by relaying one payment through all the channels...
2191         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2192         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2193         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2194         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2195
2196         // Simple case with no pending HTLCs:
2197         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2198         check_added_monitors!(nodes[1], 1);
2199         check_closed_broadcast!(nodes[1], true);
2200         {
2201                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2202                 assert_eq!(node_txn.len(), 1);
2203                 mine_transaction(&nodes[0], &node_txn[0]);
2204                 check_added_monitors!(nodes[0], 1);
2205                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2206         }
2207         check_closed_broadcast!(nodes[0], true);
2208         assert_eq!(nodes[0].node.list_channels().len(), 0);
2209         assert_eq!(nodes[1].node.list_channels().len(), 1);
2210         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2211         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2212
2213         // One pending HTLC is discarded by the force-close:
2214         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2215
2216         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2217         // broadcasted until we reach the timelock time).
2218         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2219         check_closed_broadcast!(nodes[1], true);
2220         check_added_monitors!(nodes[1], 1);
2221         {
2222                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2223                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2224                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2225                 mine_transaction(&nodes[2], &node_txn[0]);
2226                 check_added_monitors!(nodes[2], 1);
2227                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2228         }
2229         check_closed_broadcast!(nodes[2], true);
2230         assert_eq!(nodes[1].node.list_channels().len(), 0);
2231         assert_eq!(nodes[2].node.list_channels().len(), 1);
2232         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2233         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2234
2235         macro_rules! claim_funds {
2236                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2237                         {
2238                                 $node.node.claim_funds($preimage);
2239                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2240                                 check_added_monitors!($node, 1);
2241
2242                                 let events = $node.node.get_and_clear_pending_msg_events();
2243                                 assert_eq!(events.len(), 1);
2244                                 match events[0] {
2245                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2246                                                 assert!(update_add_htlcs.is_empty());
2247                                                 assert!(update_fail_htlcs.is_empty());
2248                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2249                                         },
2250                                         _ => panic!("Unexpected event"),
2251                                 };
2252                         }
2253                 }
2254         }
2255
2256         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2257         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2258         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2259         check_added_monitors!(nodes[2], 1);
2260         check_closed_broadcast!(nodes[2], true);
2261         let node2_commitment_txid;
2262         {
2263                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2264                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2265                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2266                 node2_commitment_txid = node_txn[0].txid();
2267
2268                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2269                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2270                 mine_transaction(&nodes[3], &node_txn[0]);
2271                 check_added_monitors!(nodes[3], 1);
2272                 check_preimage_claim(&nodes[3], &node_txn);
2273         }
2274         check_closed_broadcast!(nodes[3], true);
2275         assert_eq!(nodes[2].node.list_channels().len(), 0);
2276         assert_eq!(nodes[3].node.list_channels().len(), 1);
2277         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2278         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2279
2280         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2281         // confusing us in the following tests.
2282         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2283
2284         // One pending HTLC to time out:
2285         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2286         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2287         // buffer space).
2288
2289         let (close_chan_update_1, close_chan_update_2) = {
2290                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2291                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2292                 assert_eq!(events.len(), 2);
2293                 let close_chan_update_1 = match events[0] {
2294                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2295                                 msg.clone()
2296                         },
2297                         _ => panic!("Unexpected event"),
2298                 };
2299                 match events[1] {
2300                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2301                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2302                         },
2303                         _ => panic!("Unexpected event"),
2304                 }
2305                 check_added_monitors!(nodes[3], 1);
2306
2307                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2308                 {
2309                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2310                         node_txn.retain(|tx| {
2311                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2312                                         false
2313                                 } else { true }
2314                         });
2315                 }
2316
2317                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2318
2319                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2320                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2321
2322                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2323                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2324                 assert_eq!(events.len(), 2);
2325                 let close_chan_update_2 = match events[0] {
2326                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2327                                 msg.clone()
2328                         },
2329                         _ => panic!("Unexpected event"),
2330                 };
2331                 match events[1] {
2332                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2333                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2334                         },
2335                         _ => panic!("Unexpected event"),
2336                 }
2337                 check_added_monitors!(nodes[4], 1);
2338                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2339
2340                 mine_transaction(&nodes[4], &node_txn[0]);
2341                 check_preimage_claim(&nodes[4], &node_txn);
2342                 (close_chan_update_1, close_chan_update_2)
2343         };
2344         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2345         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2346         assert_eq!(nodes[3].node.list_channels().len(), 0);
2347         assert_eq!(nodes[4].node.list_channels().len(), 0);
2348
2349         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2350         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2351         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2352 }
2353
2354 #[test]
2355 fn test_justice_tx() {
2356         // Test justice txn built on revoked HTLC-Success tx, against both sides
2357         let mut alice_config = UserConfig::default();
2358         alice_config.channel_handshake_config.announced_channel = true;
2359         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2360         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2361         let mut bob_config = UserConfig::default();
2362         bob_config.channel_handshake_config.announced_channel = true;
2363         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2364         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2365         let user_cfgs = [Some(alice_config), Some(bob_config)];
2366         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2367         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2368         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2369         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2370         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2371         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2372         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2373         // Create some new channels:
2374         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2375
2376         // A pending HTLC which will be revoked:
2377         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2378         // Get the will-be-revoked local txn from nodes[0]
2379         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2380         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2381         assert_eq!(revoked_local_txn[0].input.len(), 1);
2382         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2383         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2384         assert_eq!(revoked_local_txn[1].input.len(), 1);
2385         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2386         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2387         // Revoke the old state
2388         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2389
2390         {
2391                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2392                 {
2393                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2394                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2395                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2396
2397                         check_spends!(node_txn[0], revoked_local_txn[0]);
2398                         node_txn.swap_remove(0);
2399                         node_txn.truncate(1);
2400                 }
2401                 check_added_monitors!(nodes[1], 1);
2402                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2403                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2404
2405                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2406                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2407                 // Verify broadcast of revoked HTLC-timeout
2408                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2409                 check_added_monitors!(nodes[0], 1);
2410                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2411                 // Broadcast revoked HTLC-timeout on node 1
2412                 mine_transaction(&nodes[1], &node_txn[1]);
2413                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2414         }
2415         get_announce_close_broadcast_events(&nodes, 0, 1);
2416
2417         assert_eq!(nodes[0].node.list_channels().len(), 0);
2418         assert_eq!(nodes[1].node.list_channels().len(), 0);
2419
2420         // We test justice_tx build by A on B's revoked HTLC-Success tx
2421         // Create some new channels:
2422         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2423         {
2424                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2425                 node_txn.clear();
2426         }
2427
2428         // A pending HTLC which will be revoked:
2429         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2430         // Get the will-be-revoked local txn from B
2431         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2432         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2433         assert_eq!(revoked_local_txn[0].input.len(), 1);
2434         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2435         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2436         // Revoke the old state
2437         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2438         {
2439                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2440                 {
2441                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2442                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2443                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2444
2445                         check_spends!(node_txn[0], revoked_local_txn[0]);
2446                         node_txn.swap_remove(0);
2447                 }
2448                 check_added_monitors!(nodes[0], 1);
2449                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2450
2451                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2452                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2453                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2454                 check_added_monitors!(nodes[1], 1);
2455                 mine_transaction(&nodes[0], &node_txn[1]);
2456                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2457                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2458         }
2459         get_announce_close_broadcast_events(&nodes, 0, 1);
2460         assert_eq!(nodes[0].node.list_channels().len(), 0);
2461         assert_eq!(nodes[1].node.list_channels().len(), 0);
2462 }
2463
2464 #[test]
2465 fn revoked_output_claim() {
2466         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2467         // transaction is broadcast by its counterparty
2468         let chanmon_cfgs = create_chanmon_cfgs(2);
2469         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2470         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2471         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2472         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2473         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2474         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2475         assert_eq!(revoked_local_txn.len(), 1);
2476         // Only output is the full channel value back to nodes[0]:
2477         assert_eq!(revoked_local_txn[0].output.len(), 1);
2478         // Send a payment through, updating everyone's latest commitment txn
2479         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2480
2481         // Inform nodes[1] that nodes[0] broadcast a stale tx
2482         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2483         check_added_monitors!(nodes[1], 1);
2484         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2485         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2486         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2487
2488         check_spends!(node_txn[0], revoked_local_txn[0]);
2489         check_spends!(node_txn[1], chan_1.3);
2490
2491         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2492         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2493         get_announce_close_broadcast_events(&nodes, 0, 1);
2494         check_added_monitors!(nodes[0], 1);
2495         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2496 }
2497
2498 #[test]
2499 fn claim_htlc_outputs_shared_tx() {
2500         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2501         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2502         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2503         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2504         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2505         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2506
2507         // Create some new channel:
2508         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2509
2510         // Rebalance the network to generate htlc in the two directions
2511         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2512         // 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
2513         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2514         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2515
2516         // Get the will-be-revoked local txn from node[0]
2517         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2518         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2519         assert_eq!(revoked_local_txn[0].input.len(), 1);
2520         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2521         assert_eq!(revoked_local_txn[1].input.len(), 1);
2522         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2523         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2524         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2525
2526         //Revoke the old state
2527         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2528
2529         {
2530                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2531                 check_added_monitors!(nodes[0], 1);
2532                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2533                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2534                 check_added_monitors!(nodes[1], 1);
2535                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2536                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2537                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2538
2539                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2540                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2541
2542                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2543                 check_spends!(node_txn[0], revoked_local_txn[0]);
2544
2545                 let mut witness_lens = BTreeSet::new();
2546                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2547                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2548                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2549                 assert_eq!(witness_lens.len(), 3);
2550                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2551                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2552                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2553
2554                 // Next nodes[1] broadcasts its current local tx state:
2555                 assert_eq!(node_txn[1].input.len(), 1);
2556                 check_spends!(node_txn[1], chan_1.3);
2557
2558                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2559                 // ANTI_REORG_DELAY confirmations.
2560                 mine_transaction(&nodes[1], &node_txn[0]);
2561                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2562                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2563         }
2564         get_announce_close_broadcast_events(&nodes, 0, 1);
2565         assert_eq!(nodes[0].node.list_channels().len(), 0);
2566         assert_eq!(nodes[1].node.list_channels().len(), 0);
2567 }
2568
2569 #[test]
2570 fn claim_htlc_outputs_single_tx() {
2571         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2572         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2573         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2574         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2575         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2576         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2577
2578         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2579
2580         // Rebalance the network to generate htlc in the two directions
2581         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2582         // 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
2583         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2584         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2585         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2586
2587         // Get the will-be-revoked local txn from node[0]
2588         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2589
2590         //Revoke the old state
2591         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2592
2593         {
2594                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2595                 check_added_monitors!(nodes[0], 1);
2596                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2597                 check_added_monitors!(nodes[1], 1);
2598                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2599                 let mut events = nodes[0].node.get_and_clear_pending_events();
2600                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2601                 match events.last().unwrap() {
2602                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2603                         _ => panic!("Unexpected event"),
2604                 }
2605
2606                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2607                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2608
2609                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2610                 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2611
2612                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2613                 assert_eq!(node_txn[0].input.len(), 1);
2614                 check_spends!(node_txn[0], chan_1.3);
2615                 assert_eq!(node_txn[1].input.len(), 1);
2616                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2617                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2618                 check_spends!(node_txn[1], node_txn[0]);
2619
2620                 // Justice transactions are indices 1-2-4
2621                 assert_eq!(node_txn[2].input.len(), 1);
2622                 assert_eq!(node_txn[3].input.len(), 1);
2623                 assert_eq!(node_txn[4].input.len(), 1);
2624
2625                 check_spends!(node_txn[2], revoked_local_txn[0]);
2626                 check_spends!(node_txn[3], revoked_local_txn[0]);
2627                 check_spends!(node_txn[4], revoked_local_txn[0]);
2628
2629                 let mut witness_lens = BTreeSet::new();
2630                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2631                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2632                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2633                 assert_eq!(witness_lens.len(), 3);
2634                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2635                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2636                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2637
2638                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2639                 // ANTI_REORG_DELAY confirmations.
2640                 mine_transaction(&nodes[1], &node_txn[2]);
2641                 mine_transaction(&nodes[1], &node_txn[3]);
2642                 mine_transaction(&nodes[1], &node_txn[4]);
2643                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2644                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2645         }
2646         get_announce_close_broadcast_events(&nodes, 0, 1);
2647         assert_eq!(nodes[0].node.list_channels().len(), 0);
2648         assert_eq!(nodes[1].node.list_channels().len(), 0);
2649 }
2650
2651 #[test]
2652 fn test_htlc_on_chain_success() {
2653         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2654         // the preimage backward accordingly. So here we test that ChannelManager is
2655         // broadcasting the right event to other nodes in payment path.
2656         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2657         // A --------------------> B ----------------------> C (preimage)
2658         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2659         // commitment transaction was broadcast.
2660         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2661         // towards B.
2662         // B should be able to claim via preimage if A then broadcasts its local tx.
2663         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2664         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2665         // PaymentSent event).
2666
2667         let chanmon_cfgs = create_chanmon_cfgs(3);
2668         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2669         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2670         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2671
2672         // Create some initial channels
2673         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2674         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2675
2676         // Ensure all nodes are at the same height
2677         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2678         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2679         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2680         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2681
2682         // Rebalance the network a bit by relaying one payment through all the channels...
2683         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2684         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2685
2686         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2687         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2688
2689         // Broadcast legit commitment tx from C on B's chain
2690         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2691         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2692         assert_eq!(commitment_tx.len(), 1);
2693         check_spends!(commitment_tx[0], chan_2.3);
2694         nodes[2].node.claim_funds(our_payment_preimage);
2695         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2696         nodes[2].node.claim_funds(our_payment_preimage_2);
2697         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2698         check_added_monitors!(nodes[2], 2);
2699         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2700         assert!(updates.update_add_htlcs.is_empty());
2701         assert!(updates.update_fail_htlcs.is_empty());
2702         assert!(updates.update_fail_malformed_htlcs.is_empty());
2703         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2704
2705         mine_transaction(&nodes[2], &commitment_tx[0]);
2706         check_closed_broadcast!(nodes[2], true);
2707         check_added_monitors!(nodes[2], 1);
2708         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2709         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)
2710         assert_eq!(node_txn.len(), 5);
2711         assert_eq!(node_txn[0], node_txn[3]);
2712         assert_eq!(node_txn[1], node_txn[4]);
2713         assert_eq!(node_txn[2], commitment_tx[0]);
2714         check_spends!(node_txn[0], commitment_tx[0]);
2715         check_spends!(node_txn[1], commitment_tx[0]);
2716         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2717         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2718         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2719         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2720         assert_eq!(node_txn[0].lock_time, 0);
2721         assert_eq!(node_txn[1].lock_time, 0);
2722
2723         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2724         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2725         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2726         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2727         {
2728                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2729                 assert_eq!(added_monitors.len(), 1);
2730                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2731                 added_monitors.clear();
2732         }
2733         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2734         assert_eq!(forwarded_events.len(), 3);
2735         match forwarded_events[0] {
2736                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2737                 _ => panic!("Unexpected event"),
2738         }
2739         let chan_id = Some(chan_1.2);
2740         match forwarded_events[1] {
2741                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2742                         assert_eq!(fee_earned_msat, Some(1000));
2743                         assert_eq!(prev_channel_id, chan_id);
2744                         assert_eq!(claim_from_onchain_tx, true);
2745                         assert_eq!(next_channel_id, Some(chan_2.2));
2746                 },
2747                 _ => panic!()
2748         }
2749         match forwarded_events[2] {
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         let events = nodes[1].node.get_and_clear_pending_msg_events();
2759         {
2760                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2761                 assert_eq!(added_monitors.len(), 2);
2762                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2763                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2764                 added_monitors.clear();
2765         }
2766         assert_eq!(events.len(), 3);
2767         match events[0] {
2768                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2769                 _ => panic!("Unexpected event"),
2770         }
2771         match events[1] {
2772                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2773                 _ => panic!("Unexpected event"),
2774         }
2775
2776         match events[2] {
2777                 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, .. } } => {
2778                         assert!(update_add_htlcs.is_empty());
2779                         assert!(update_fail_htlcs.is_empty());
2780                         assert_eq!(update_fulfill_htlcs.len(), 1);
2781                         assert!(update_fail_malformed_htlcs.is_empty());
2782                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2783                 },
2784                 _ => panic!("Unexpected event"),
2785         };
2786         macro_rules! check_tx_local_broadcast {
2787                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2788                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2789                         assert_eq!(node_txn.len(), 3);
2790                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2791                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2792                         check_spends!(node_txn[1], $commitment_tx);
2793                         check_spends!(node_txn[2], $commitment_tx);
2794                         assert_ne!(node_txn[1].lock_time, 0);
2795                         assert_ne!(node_txn[2].lock_time, 0);
2796                         if $htlc_offered {
2797                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2798                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2799                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2800                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2801                         } else {
2802                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2803                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2804                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2805                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2806                         }
2807                         check_spends!(node_txn[0], $chan_tx);
2808                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2809                         node_txn.clear();
2810                 } }
2811         }
2812         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2813         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2814         // timeout-claim of the output that nodes[2] just claimed via success.
2815         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2816
2817         // Broadcast legit commitment tx from A on B's chain
2818         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2819         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2820         check_spends!(node_a_commitment_tx[0], chan_1.3);
2821         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2822         check_closed_broadcast!(nodes[1], true);
2823         check_added_monitors!(nodes[1], 1);
2824         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2825         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2826         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2827         let commitment_spend =
2828                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2829                         check_spends!(node_txn[1], commitment_tx[0]);
2830                         check_spends!(node_txn[2], commitment_tx[0]);
2831                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2832                         &node_txn[0]
2833                 } else {
2834                         check_spends!(node_txn[0], commitment_tx[0]);
2835                         check_spends!(node_txn[1], commitment_tx[0]);
2836                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2837                         &node_txn[2]
2838                 };
2839
2840         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2841         assert_eq!(commitment_spend.input.len(), 2);
2842         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2843         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2844         assert_eq!(commitment_spend.lock_time, 0);
2845         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2846         check_spends!(node_txn[3], chan_1.3);
2847         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2848         check_spends!(node_txn[4], node_txn[3]);
2849         check_spends!(node_txn[5], node_txn[3]);
2850         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2851         // we already checked the same situation with A.
2852
2853         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2854         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2855         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2856         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2857         check_closed_broadcast!(nodes[0], true);
2858         check_added_monitors!(nodes[0], 1);
2859         let events = nodes[0].node.get_and_clear_pending_events();
2860         assert_eq!(events.len(), 5);
2861         let mut first_claimed = false;
2862         for event in events {
2863                 match event {
2864                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2865                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2866                                         assert!(!first_claimed);
2867                                         first_claimed = true;
2868                                 } else {
2869                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2870                                         assert_eq!(payment_hash, payment_hash_2);
2871                                 }
2872                         },
2873                         Event::PaymentPathSuccessful { .. } => {},
2874                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2875                         _ => panic!("Unexpected event"),
2876                 }
2877         }
2878         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2879 }
2880
2881 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2882         // Test that in case of a unilateral close onchain, we detect the state of output and
2883         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2884         // broadcasting the right event to other nodes in payment path.
2885         // A ------------------> B ----------------------> C (timeout)
2886         //    B's commitment tx                 C's commitment tx
2887         //            \                                  \
2888         //         B's HTLC timeout tx               B's timeout tx
2889
2890         let chanmon_cfgs = create_chanmon_cfgs(3);
2891         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2892         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2893         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2894         *nodes[0].connect_style.borrow_mut() = connect_style;
2895         *nodes[1].connect_style.borrow_mut() = connect_style;
2896         *nodes[2].connect_style.borrow_mut() = connect_style;
2897
2898         // Create some intial channels
2899         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2900         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2901
2902         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2903         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2904         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2905
2906         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2907
2908         // Broadcast legit commitment tx from C on B's chain
2909         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2910         check_spends!(commitment_tx[0], chan_2.3);
2911         nodes[2].node.fail_htlc_backwards(&payment_hash);
2912         check_added_monitors!(nodes[2], 0);
2913         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2914         check_added_monitors!(nodes[2], 1);
2915
2916         let events = nodes[2].node.get_and_clear_pending_msg_events();
2917         assert_eq!(events.len(), 1);
2918         match events[0] {
2919                 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, .. } } => {
2920                         assert!(update_add_htlcs.is_empty());
2921                         assert!(!update_fail_htlcs.is_empty());
2922                         assert!(update_fulfill_htlcs.is_empty());
2923                         assert!(update_fail_malformed_htlcs.is_empty());
2924                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2925                 },
2926                 _ => panic!("Unexpected event"),
2927         };
2928         mine_transaction(&nodes[2], &commitment_tx[0]);
2929         check_closed_broadcast!(nodes[2], true);
2930         check_added_monitors!(nodes[2], 1);
2931         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2932         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2933         assert_eq!(node_txn.len(), 1);
2934         check_spends!(node_txn[0], chan_2.3);
2935         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2936
2937         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2938         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2939         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2940         mine_transaction(&nodes[1], &commitment_tx[0]);
2941         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2942         let timeout_tx;
2943         {
2944                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2945                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2946                 assert_eq!(node_txn[0], node_txn[3]);
2947                 assert_eq!(node_txn[1], node_txn[4]);
2948
2949                 check_spends!(node_txn[2], commitment_tx[0]);
2950                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2951
2952                 check_spends!(node_txn[0], chan_2.3);
2953                 check_spends!(node_txn[1], node_txn[0]);
2954                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2955                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2956
2957                 timeout_tx = node_txn[2].clone();
2958                 node_txn.clear();
2959         }
2960
2961         mine_transaction(&nodes[1], &timeout_tx);
2962         check_added_monitors!(nodes[1], 1);
2963         check_closed_broadcast!(nodes[1], true);
2964         {
2965                 // B will rebroadcast a fee-bumped timeout transaction here.
2966                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2967                 assert_eq!(node_txn.len(), 1);
2968                 check_spends!(node_txn[0], commitment_tx[0]);
2969         }
2970
2971         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2972         {
2973                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2974                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2975                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2976                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2977                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2978                 if node_txn.len() == 1 {
2979                         check_spends!(node_txn[0], chan_2.3);
2980                 } else {
2981                         assert_eq!(node_txn.len(), 0);
2982                 }
2983         }
2984
2985         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
2986         check_added_monitors!(nodes[1], 1);
2987         let events = nodes[1].node.get_and_clear_pending_msg_events();
2988         assert_eq!(events.len(), 1);
2989         match events[0] {
2990                 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, .. } } => {
2991                         assert!(update_add_htlcs.is_empty());
2992                         assert!(!update_fail_htlcs.is_empty());
2993                         assert!(update_fulfill_htlcs.is_empty());
2994                         assert!(update_fail_malformed_htlcs.is_empty());
2995                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2996                 },
2997                 _ => panic!("Unexpected event"),
2998         };
2999
3000         // Broadcast legit commitment tx from B on A's chain
3001         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3002         check_spends!(commitment_tx[0], chan_1.3);
3003
3004         mine_transaction(&nodes[0], &commitment_tx[0]);
3005         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3006
3007         check_closed_broadcast!(nodes[0], true);
3008         check_added_monitors!(nodes[0], 1);
3009         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3010         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3011         assert_eq!(node_txn.len(), 2);
3012         check_spends!(node_txn[0], chan_1.3);
3013         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3014         check_spends!(node_txn[1], commitment_tx[0]);
3015         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3016 }
3017
3018 #[test]
3019 fn test_htlc_on_chain_timeout() {
3020         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3021         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3022         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3023 }
3024
3025 #[test]
3026 fn test_simple_commitment_revoked_fail_backward() {
3027         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3028         // and fail backward accordingly.
3029
3030         let chanmon_cfgs = create_chanmon_cfgs(3);
3031         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3032         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3033         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3034
3035         // Create some initial channels
3036         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3037         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3038
3039         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3040         // Get the will-be-revoked local txn from nodes[2]
3041         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3042         // Revoke the old state
3043         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3044
3045         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3046
3047         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3048         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3049         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3050         check_added_monitors!(nodes[1], 1);
3051         check_closed_broadcast!(nodes[1], true);
3052
3053         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
3054         check_added_monitors!(nodes[1], 1);
3055         let events = nodes[1].node.get_and_clear_pending_msg_events();
3056         assert_eq!(events.len(), 1);
3057         match events[0] {
3058                 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, .. } } => {
3059                         assert!(update_add_htlcs.is_empty());
3060                         assert_eq!(update_fail_htlcs.len(), 1);
3061                         assert!(update_fulfill_htlcs.is_empty());
3062                         assert!(update_fail_malformed_htlcs.is_empty());
3063                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3064
3065                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3066                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3067                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3068                 },
3069                 _ => panic!("Unexpected event"),
3070         }
3071 }
3072
3073 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3074         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3075         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3076         // commitment transaction anymore.
3077         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3078         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3079         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3080         // technically disallowed and we should probably handle it reasonably.
3081         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3082         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3083         // transactions:
3084         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3085         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3086         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3087         //   and once they revoke the previous commitment transaction (allowing us to send a new
3088         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3089         let chanmon_cfgs = create_chanmon_cfgs(3);
3090         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3091         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3092         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3093
3094         // Create some initial channels
3095         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3096         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3097
3098         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 });
3099         // Get the will-be-revoked local txn from nodes[2]
3100         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3101         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3102         // Revoke the old state
3103         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3104
3105         let value = if use_dust {
3106                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3107                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3108                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3109         } else { 3000000 };
3110
3111         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3112         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3113         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3114
3115         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3116         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3117         check_added_monitors!(nodes[2], 1);
3118         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3119         assert!(updates.update_add_htlcs.is_empty());
3120         assert!(updates.update_fulfill_htlcs.is_empty());
3121         assert!(updates.update_fail_malformed_htlcs.is_empty());
3122         assert_eq!(updates.update_fail_htlcs.len(), 1);
3123         assert!(updates.update_fee.is_none());
3124         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3125         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3126         // Drop the last RAA from 3 -> 2
3127
3128         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3129         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3130         check_added_monitors!(nodes[2], 1);
3131         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3132         assert!(updates.update_add_htlcs.is_empty());
3133         assert!(updates.update_fulfill_htlcs.is_empty());
3134         assert!(updates.update_fail_malformed_htlcs.is_empty());
3135         assert_eq!(updates.update_fail_htlcs.len(), 1);
3136         assert!(updates.update_fee.is_none());
3137         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3138         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3139         check_added_monitors!(nodes[1], 1);
3140         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3141         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3142         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3143         check_added_monitors!(nodes[2], 1);
3144
3145         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3146         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3147         check_added_monitors!(nodes[2], 1);
3148         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3149         assert!(updates.update_add_htlcs.is_empty());
3150         assert!(updates.update_fulfill_htlcs.is_empty());
3151         assert!(updates.update_fail_malformed_htlcs.is_empty());
3152         assert_eq!(updates.update_fail_htlcs.len(), 1);
3153         assert!(updates.update_fee.is_none());
3154         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3155         // At this point first_payment_hash has dropped out of the latest two commitment
3156         // transactions that nodes[1] is tracking...
3157         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3158         check_added_monitors!(nodes[1], 1);
3159         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3160         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3161         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3162         check_added_monitors!(nodes[2], 1);
3163
3164         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3165         // on nodes[2]'s RAA.
3166         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3167         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3168         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3169         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3170         check_added_monitors!(nodes[1], 0);
3171
3172         if deliver_bs_raa {
3173                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3174                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3175                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3176                 check_added_monitors!(nodes[1], 1);
3177                 let events = nodes[1].node.get_and_clear_pending_events();
3178                 assert_eq!(events.len(), 2);
3179                 match events[0] {
3180                         Event::PendingHTLCsForwardable { .. } => { },
3181                         _ => panic!("Unexpected event"),
3182                 };
3183                 match events[1] {
3184                         Event::HTLCHandlingFailed { .. } => { },
3185                         _ => panic!("Unexpected event"),
3186                 }
3187                 // Deliberately don't process the pending fail-back so they all fail back at once after
3188                 // block connection just like the !deliver_bs_raa case
3189         }
3190
3191         let mut failed_htlcs = HashSet::new();
3192         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3193
3194         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3195         check_added_monitors!(nodes[1], 1);
3196         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3197         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3198
3199         let events = nodes[1].node.get_and_clear_pending_events();
3200         assert_eq!(events.len(), if deliver_bs_raa { 2 + (nodes.len() - 1) } else { 4 + nodes.len() });
3201         match events[0] {
3202                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3203                 _ => panic!("Unexepected event"),
3204         }
3205         match events[1] {
3206                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3207                         assert_eq!(*payment_hash, fourth_payment_hash);
3208                 },
3209                 _ => panic!("Unexpected event"),
3210         }
3211         if !deliver_bs_raa {
3212                 match events[2] {
3213                         Event::PaymentFailed { ref payment_hash, .. } => {
3214                                 assert_eq!(*payment_hash, fourth_payment_hash);
3215                         },
3216                         _ => panic!("Unexpected event"),
3217                 }
3218                 match events[3] {
3219                         Event::PendingHTLCsForwardable { .. } => { },
3220                         _ => panic!("Unexpected event"),
3221                 };
3222         }
3223         nodes[1].node.process_pending_htlc_forwards();
3224         check_added_monitors!(nodes[1], 1);
3225
3226         let events = nodes[1].node.get_and_clear_pending_msg_events();
3227         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3228         match events[if deliver_bs_raa { 1 } else { 0 }] {
3229                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3230                 _ => panic!("Unexpected event"),
3231         }
3232         match events[if deliver_bs_raa { 2 } else { 1 }] {
3233                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3234                         assert_eq!(channel_id, chan_2.2);
3235                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3236                 },
3237                 _ => panic!("Unexpected event"),
3238         }
3239         if deliver_bs_raa {
3240                 match events[0] {
3241                         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, .. } } => {
3242                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3243                                 assert_eq!(update_add_htlcs.len(), 1);
3244                                 assert!(update_fulfill_htlcs.is_empty());
3245                                 assert!(update_fail_htlcs.is_empty());
3246                                 assert!(update_fail_malformed_htlcs.is_empty());
3247                         },
3248                         _ => panic!("Unexpected event"),
3249                 }
3250         }
3251         match events[if deliver_bs_raa { 3 } else { 2 }] {
3252                 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, .. } } => {
3253                         assert!(update_add_htlcs.is_empty());
3254                         assert_eq!(update_fail_htlcs.len(), 3);
3255                         assert!(update_fulfill_htlcs.is_empty());
3256                         assert!(update_fail_malformed_htlcs.is_empty());
3257                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3258
3259                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3260                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3261                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3262
3263                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3264
3265                         let events = nodes[0].node.get_and_clear_pending_events();
3266                         assert_eq!(events.len(), 3);
3267                         match events[0] {
3268                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3269                                         assert!(failed_htlcs.insert(payment_hash.0));
3270                                         // If we delivered B's RAA we got an unknown preimage error, not something
3271                                         // that we should update our routing table for.
3272                                         if !deliver_bs_raa {
3273                                                 assert!(network_update.is_some());
3274                                         }
3275                                 },
3276                                 _ => panic!("Unexpected event"),
3277                         }
3278                         match events[1] {
3279                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3280                                         assert!(failed_htlcs.insert(payment_hash.0));
3281                                         assert!(network_update.is_some());
3282                                 },
3283                                 _ => panic!("Unexpected event"),
3284                         }
3285                         match events[2] {
3286                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3287                                         assert!(failed_htlcs.insert(payment_hash.0));
3288                                         assert!(network_update.is_some());
3289                                 },
3290                                 _ => panic!("Unexpected event"),
3291                         }
3292                 },
3293                 _ => panic!("Unexpected event"),
3294         }
3295
3296         assert!(failed_htlcs.contains(&first_payment_hash.0));
3297         assert!(failed_htlcs.contains(&second_payment_hash.0));
3298         assert!(failed_htlcs.contains(&third_payment_hash.0));
3299 }
3300
3301 #[test]
3302 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3303         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3304         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3305         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3306         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3307 }
3308
3309 #[test]
3310 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3311         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3312         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3313         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3314         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3315 }
3316
3317 #[test]
3318 fn fail_backward_pending_htlc_upon_channel_failure() {
3319         let chanmon_cfgs = create_chanmon_cfgs(2);
3320         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3321         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3322         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3323         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3324
3325         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3326         {
3327                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3328                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3329                 check_added_monitors!(nodes[0], 1);
3330
3331                 let payment_event = {
3332                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3333                         assert_eq!(events.len(), 1);
3334                         SendEvent::from_event(events.remove(0))
3335                 };
3336                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3337                 assert_eq!(payment_event.msgs.len(), 1);
3338         }
3339
3340         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3341         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3342         {
3343                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3344                 check_added_monitors!(nodes[0], 0);
3345
3346                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3347         }
3348
3349         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3350         {
3351                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3352
3353                 let secp_ctx = Secp256k1::new();
3354                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3355                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3356                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3357                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3358                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3359
3360                 // Send a 0-msat update_add_htlc to fail the channel.
3361                 let update_add_htlc = msgs::UpdateAddHTLC {
3362                         channel_id: chan.2,
3363                         htlc_id: 0,
3364                         amount_msat: 0,
3365                         payment_hash,
3366                         cltv_expiry,
3367                         onion_routing_packet,
3368                 };
3369                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3370         }
3371         let events = nodes[0].node.get_and_clear_pending_events();
3372         assert_eq!(events.len(), 2);
3373         // Check that Alice fails backward the pending HTLC from the second payment.
3374         match events[0] {
3375                 Event::PaymentPathFailed { payment_hash, .. } => {
3376                         assert_eq!(payment_hash, failed_payment_hash);
3377                 },
3378                 _ => panic!("Unexpected event"),
3379         }
3380         match events[1] {
3381                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3382                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3383                 },
3384                 _ => panic!("Unexpected event {:?}", events[1]),
3385         }
3386         check_closed_broadcast!(nodes[0], true);
3387         check_added_monitors!(nodes[0], 1);
3388 }
3389
3390 #[test]
3391 fn test_htlc_ignore_latest_remote_commitment() {
3392         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3393         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3394         let chanmon_cfgs = create_chanmon_cfgs(2);
3395         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3396         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3397         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3398         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3399
3400         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3401         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3402         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3403         check_closed_broadcast!(nodes[0], true);
3404         check_added_monitors!(nodes[0], 1);
3405         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3406
3407         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3408         assert_eq!(node_txn.len(), 3);
3409         assert_eq!(node_txn[0], node_txn[1]);
3410
3411         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3412         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3413         check_closed_broadcast!(nodes[1], true);
3414         check_added_monitors!(nodes[1], 1);
3415         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3416
3417         // Duplicate the connect_block call since this may happen due to other listeners
3418         // registering new transactions
3419         header.prev_blockhash = header.block_hash();
3420         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3421 }
3422
3423 #[test]
3424 fn test_force_close_fail_back() {
3425         // Check which HTLCs are failed-backwards on channel force-closure
3426         let chanmon_cfgs = create_chanmon_cfgs(3);
3427         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3428         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3429         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3430         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3431         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3432
3433         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3434
3435         let mut payment_event = {
3436                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3437                 check_added_monitors!(nodes[0], 1);
3438
3439                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3440                 assert_eq!(events.len(), 1);
3441                 SendEvent::from_event(events.remove(0))
3442         };
3443
3444         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3445         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3446
3447         expect_pending_htlcs_forwardable!(nodes[1]);
3448
3449         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3450         assert_eq!(events_2.len(), 1);
3451         payment_event = SendEvent::from_event(events_2.remove(0));
3452         assert_eq!(payment_event.msgs.len(), 1);
3453
3454         check_added_monitors!(nodes[1], 1);
3455         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3456         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3457         check_added_monitors!(nodes[2], 1);
3458         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3459
3460         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3461         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3462         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3463
3464         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3465         check_closed_broadcast!(nodes[2], true);
3466         check_added_monitors!(nodes[2], 1);
3467         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3468         let tx = {
3469                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3470                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3471                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3472                 // back to nodes[1] upon timeout otherwise.
3473                 assert_eq!(node_txn.len(), 1);
3474                 node_txn.remove(0)
3475         };
3476
3477         mine_transaction(&nodes[1], &tx);
3478
3479         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3480         check_closed_broadcast!(nodes[1], true);
3481         check_added_monitors!(nodes[1], 1);
3482         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3483
3484         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3485         {
3486                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3487                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &LowerBoundedFeeEstimator::new(node_cfgs[2].fee_estimator), &node_cfgs[2].logger);
3488         }
3489         mine_transaction(&nodes[2], &tx);
3490         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3491         assert_eq!(node_txn.len(), 1);
3492         assert_eq!(node_txn[0].input.len(), 1);
3493         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3494         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3495         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3496
3497         check_spends!(node_txn[0], tx);
3498 }
3499
3500 #[test]
3501 fn test_dup_events_on_peer_disconnect() {
3502         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3503         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3504         // as we used to generate the event immediately upon receipt of the payment preimage in the
3505         // update_fulfill_htlc message.
3506
3507         let chanmon_cfgs = create_chanmon_cfgs(2);
3508         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3509         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3510         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3511         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3512
3513         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3514
3515         nodes[1].node.claim_funds(payment_preimage);
3516         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3517         check_added_monitors!(nodes[1], 1);
3518         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3519         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3520         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3521
3522         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3523         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3524
3525         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3526         expect_payment_path_successful!(nodes[0]);
3527 }
3528
3529 #[test]
3530 fn test_peer_disconnected_before_funding_broadcasted() {
3531         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3532         // before the funding transaction has been broadcasted.
3533         let chanmon_cfgs = create_chanmon_cfgs(2);
3534         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3535         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3536         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3537
3538         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3539         // broadcasted, even though it's created by `nodes[0]`.
3540         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();
3541         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3542         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3543         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3544         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3545
3546         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3547         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3548
3549         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3550
3551         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3552         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3553
3554         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3555         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3556         // broadcasted.
3557         {
3558                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3559         }
3560
3561         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3562         // disconnected before the funding transaction was broadcasted.
3563         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3564         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3565
3566         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3567         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3568 }
3569
3570 #[test]
3571 fn test_simple_peer_disconnect() {
3572         // Test that we can reconnect when there are no lost messages
3573         let chanmon_cfgs = create_chanmon_cfgs(3);
3574         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3575         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3576         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3577         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3578         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3579
3580         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3581         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3582         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3583
3584         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3585         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3586         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3587         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3588
3589         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3590         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3591         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3592
3593         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3594         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3595         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3596         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3597
3598         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3599         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3600
3601         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3602         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3603
3604         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3605         {
3606                 let events = nodes[0].node.get_and_clear_pending_events();
3607                 assert_eq!(events.len(), 3);
3608                 match events[0] {
3609                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3610                                 assert_eq!(payment_preimage, payment_preimage_3);
3611                                 assert_eq!(payment_hash, payment_hash_3);
3612                         },
3613                         _ => panic!("Unexpected event"),
3614                 }
3615                 match events[1] {
3616                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3617                                 assert_eq!(payment_hash, payment_hash_5);
3618                                 assert!(rejected_by_dest);
3619                         },
3620                         _ => panic!("Unexpected event"),
3621                 }
3622                 match events[2] {
3623                         Event::PaymentPathSuccessful { .. } => {},
3624                         _ => panic!("Unexpected event"),
3625                 }
3626         }
3627
3628         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3629         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3630 }
3631
3632 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3633         // Test that we can reconnect when in-flight HTLC updates get dropped
3634         let chanmon_cfgs = create_chanmon_cfgs(2);
3635         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3636         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3637         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3638
3639         let mut as_channel_ready = None;
3640         if messages_delivered == 0 {
3641                 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3642                 as_channel_ready = Some(channel_ready);
3643                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3644                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3645                 // it before the channel_reestablish message.
3646         } else {
3647                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3648         }
3649
3650         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3651
3652         let payment_event = {
3653                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3654                 check_added_monitors!(nodes[0], 1);
3655
3656                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3657                 assert_eq!(events.len(), 1);
3658                 SendEvent::from_event(events.remove(0))
3659         };
3660         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3661
3662         if messages_delivered < 2 {
3663                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3664         } else {
3665                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3666                 if messages_delivered >= 3 {
3667                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3668                         check_added_monitors!(nodes[1], 1);
3669                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3670
3671                         if messages_delivered >= 4 {
3672                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3673                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3674                                 check_added_monitors!(nodes[0], 1);
3675
3676                                 if messages_delivered >= 5 {
3677                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3678                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3679                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3680                                         check_added_monitors!(nodes[0], 1);
3681
3682                                         if messages_delivered >= 6 {
3683                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3684                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3685                                                 check_added_monitors!(nodes[1], 1);
3686                                         }
3687                                 }
3688                         }
3689                 }
3690         }
3691
3692         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3693         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3694         if messages_delivered < 3 {
3695                 if simulate_broken_lnd {
3696                         // lnd has a long-standing bug where they send a channel_ready prior to a
3697                         // channel_reestablish if you reconnect prior to channel_ready time.
3698                         //
3699                         // Here we simulate that behavior, delivering a channel_ready immediately on
3700                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3701                         // in `reconnect_nodes` but we currently don't fail based on that.
3702                         //
3703                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3704                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3705                 }
3706                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3707                 // received on either side, both sides will need to resend them.
3708                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3709         } else if messages_delivered == 3 {
3710                 // nodes[0] still wants its RAA + commitment_signed
3711                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3712         } else if messages_delivered == 4 {
3713                 // nodes[0] still wants its commitment_signed
3714                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3715         } else if messages_delivered == 5 {
3716                 // nodes[1] still wants its final RAA
3717                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3718         } else if messages_delivered == 6 {
3719                 // Everything was delivered...
3720                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3721         }
3722
3723         let events_1 = nodes[1].node.get_and_clear_pending_events();
3724         assert_eq!(events_1.len(), 1);
3725         match events_1[0] {
3726                 Event::PendingHTLCsForwardable { .. } => { },
3727                 _ => panic!("Unexpected event"),
3728         };
3729
3730         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3731         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3732         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3733
3734         nodes[1].node.process_pending_htlc_forwards();
3735
3736         let events_2 = nodes[1].node.get_and_clear_pending_events();
3737         assert_eq!(events_2.len(), 1);
3738         match events_2[0] {
3739                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3740                         assert_eq!(payment_hash_1, *payment_hash);
3741                         assert_eq!(amount_msat, 1_000_000);
3742                         match &purpose {
3743                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3744                                         assert!(payment_preimage.is_none());
3745                                         assert_eq!(payment_secret_1, *payment_secret);
3746                                 },
3747                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3748                         }
3749                 },
3750                 _ => panic!("Unexpected event"),
3751         }
3752
3753         nodes[1].node.claim_funds(payment_preimage_1);
3754         check_added_monitors!(nodes[1], 1);
3755         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3756
3757         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3758         assert_eq!(events_3.len(), 1);
3759         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3760                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3761                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3762                         assert!(updates.update_add_htlcs.is_empty());
3763                         assert!(updates.update_fail_htlcs.is_empty());
3764                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3765                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3766                         assert!(updates.update_fee.is_none());
3767                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3768                 },
3769                 _ => panic!("Unexpected event"),
3770         };
3771
3772         if messages_delivered >= 1 {
3773                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3774
3775                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3776                 assert_eq!(events_4.len(), 1);
3777                 match events_4[0] {
3778                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3779                                 assert_eq!(payment_preimage_1, *payment_preimage);
3780                                 assert_eq!(payment_hash_1, *payment_hash);
3781                         },
3782                         _ => panic!("Unexpected event"),
3783                 }
3784
3785                 if messages_delivered >= 2 {
3786                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3787                         check_added_monitors!(nodes[0], 1);
3788                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3789
3790                         if messages_delivered >= 3 {
3791                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3792                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3793                                 check_added_monitors!(nodes[1], 1);
3794
3795                                 if messages_delivered >= 4 {
3796                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3797                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3798                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3799                                         check_added_monitors!(nodes[1], 1);
3800
3801                                         if messages_delivered >= 5 {
3802                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3803                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3804                                                 check_added_monitors!(nodes[0], 1);
3805                                         }
3806                                 }
3807                         }
3808                 }
3809         }
3810
3811         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3812         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3813         if messages_delivered < 2 {
3814                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3815                 if messages_delivered < 1 {
3816                         expect_payment_sent!(nodes[0], payment_preimage_1);
3817                 } else {
3818                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3819                 }
3820         } else if messages_delivered == 2 {
3821                 // nodes[0] still wants its RAA + commitment_signed
3822                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3823         } else if messages_delivered == 3 {
3824                 // nodes[0] still wants its commitment_signed
3825                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3826         } else if messages_delivered == 4 {
3827                 // nodes[1] still wants its final RAA
3828                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3829         } else if messages_delivered == 5 {
3830                 // Everything was delivered...
3831                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3832         }
3833
3834         if messages_delivered == 1 || messages_delivered == 2 {
3835                 expect_payment_path_successful!(nodes[0]);
3836         }
3837
3838         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3839         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3840         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3841
3842         if messages_delivered > 2 {
3843                 expect_payment_path_successful!(nodes[0]);
3844         }
3845
3846         // Channel should still work fine...
3847         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3848         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3849         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3850 }
3851
3852 #[test]
3853 fn test_drop_messages_peer_disconnect_a() {
3854         do_test_drop_messages_peer_disconnect(0, true);
3855         do_test_drop_messages_peer_disconnect(0, false);
3856         do_test_drop_messages_peer_disconnect(1, false);
3857         do_test_drop_messages_peer_disconnect(2, false);
3858 }
3859
3860 #[test]
3861 fn test_drop_messages_peer_disconnect_b() {
3862         do_test_drop_messages_peer_disconnect(3, false);
3863         do_test_drop_messages_peer_disconnect(4, false);
3864         do_test_drop_messages_peer_disconnect(5, false);
3865         do_test_drop_messages_peer_disconnect(6, false);
3866 }
3867
3868 #[test]
3869 fn test_funding_peer_disconnect() {
3870         // Test that we can lock in our funding tx while disconnected
3871         let chanmon_cfgs = create_chanmon_cfgs(2);
3872         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3873         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3874         let persister: test_utils::TestPersister;
3875         let new_chain_monitor: test_utils::TestChainMonitor;
3876         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3877         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3878         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3879
3880         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3881         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3882
3883         confirm_transaction(&nodes[0], &tx);
3884         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3885         assert!(events_1.is_empty());
3886
3887         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3888
3889         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3890         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3891
3892         confirm_transaction(&nodes[1], &tx);
3893         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3894         assert!(events_2.is_empty());
3895
3896         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3897         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3898         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3899         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3900
3901         // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3902         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3903         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3904         assert_eq!(events_3.len(), 1);
3905         let as_channel_ready = match events_3[0] {
3906                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3907                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3908                         msg.clone()
3909                 },
3910                 _ => panic!("Unexpected event {:?}", events_3[0]),
3911         };
3912
3913         // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3914         // announcement_signatures as well as channel_update.
3915         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3916         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3917         assert_eq!(events_4.len(), 3);
3918         let chan_id;
3919         let bs_channel_ready = match events_4[0] {
3920                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3921                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3922                         chan_id = msg.channel_id;
3923                         msg.clone()
3924                 },
3925                 _ => panic!("Unexpected event {:?}", events_4[0]),
3926         };
3927         let bs_announcement_sigs = match events_4[1] {
3928                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3929                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3930                         msg.clone()
3931                 },
3932                 _ => panic!("Unexpected event {:?}", events_4[1]),
3933         };
3934         match events_4[2] {
3935                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3936                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3937                 },
3938                 _ => panic!("Unexpected event {:?}", events_4[2]),
3939         }
3940
3941         // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3942         // generates a duplicative private channel_update
3943         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3944         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3945         assert_eq!(events_5.len(), 1);
3946         match events_5[0] {
3947                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3948                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3949                 },
3950                 _ => panic!("Unexpected event {:?}", events_5[0]),
3951         };
3952
3953         // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3954         // announcement_signatures.
3955         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3956         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3957         assert_eq!(events_6.len(), 1);
3958         let as_announcement_sigs = match events_6[0] {
3959                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3960                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3961                         msg.clone()
3962                 },
3963                 _ => panic!("Unexpected event {:?}", events_6[0]),
3964         };
3965
3966         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3967         // broadcast the channel announcement globally, as well as re-send its (now-public)
3968         // channel_update.
3969         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3970         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3971         assert_eq!(events_7.len(), 1);
3972         let (chan_announcement, as_update) = match events_7[0] {
3973                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3974                         (msg.clone(), update_msg.clone())
3975                 },
3976                 _ => panic!("Unexpected event {:?}", events_7[0]),
3977         };
3978
3979         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3980         // same channel_announcement.
3981         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3982         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3983         assert_eq!(events_8.len(), 1);
3984         let bs_update = match events_8[0] {
3985                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3986                         assert_eq!(*msg, chan_announcement);
3987                         update_msg.clone()
3988                 },
3989                 _ => panic!("Unexpected event {:?}", events_8[0]),
3990         };
3991
3992         // Provide the channel announcement and public updates to the network graph
3993         nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3994         nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
3995         nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
3996
3997         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3998         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3999         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
4000
4001         // Check that after deserialization and reconnection we can still generate an identical
4002         // channel_announcement from the cached signatures.
4003         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4004
4005         let nodes_0_serialized = nodes[0].node.encode();
4006         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4007         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4008
4009         persister = test_utils::TestPersister::new();
4010         let keys_manager = &chanmon_cfgs[0].keys_manager;
4011         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);
4012         nodes[0].chain_monitor = &new_chain_monitor;
4013         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4014         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4015                 &mut chan_0_monitor_read, keys_manager).unwrap();
4016         assert!(chan_0_monitor_read.is_empty());
4017
4018         let mut nodes_0_read = &nodes_0_serialized[..];
4019         let (_, nodes_0_deserialized_tmp) = {
4020                 let mut channel_monitors = HashMap::new();
4021                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4022                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4023                         default_config: UserConfig::default(),
4024                         keys_manager,
4025                         fee_estimator: node_cfgs[0].fee_estimator,
4026                         chain_monitor: nodes[0].chain_monitor,
4027                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4028                         logger: nodes[0].logger,
4029                         channel_monitors,
4030                 }).unwrap()
4031         };
4032         nodes_0_deserialized = nodes_0_deserialized_tmp;
4033         assert!(nodes_0_read.is_empty());
4034
4035         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4036         nodes[0].node = &nodes_0_deserialized;
4037         check_added_monitors!(nodes[0], 1);
4038
4039         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4040
4041         // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4042         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4043         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4044         let mut found_announcement = false;
4045         for event in msgs.iter() {
4046                 match event {
4047                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4048                                 if *msg == chan_announcement { found_announcement = true; }
4049                         },
4050                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4051                         _ => panic!("Unexpected event"),
4052                 }
4053         }
4054         assert!(found_announcement);
4055 }
4056
4057 #[test]
4058 fn test_channel_ready_without_best_block_updated() {
4059         // Previously, if we were offline when a funding transaction was locked in, and then we came
4060         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4061         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4062         // channel_ready immediately instead.
4063         let chanmon_cfgs = create_chanmon_cfgs(2);
4064         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4065         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4066         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4067         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4068
4069         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4070
4071         let conf_height = nodes[0].best_block_info().1 + 1;
4072         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4073         let block_txn = [funding_tx];
4074         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4075         let conf_block_header = nodes[0].get_block_header(conf_height);
4076         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4077
4078         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4079         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4080         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4081 }
4082
4083 #[test]
4084 fn test_drop_messages_peer_disconnect_dual_htlc() {
4085         // Test that we can handle reconnecting when both sides of a channel have pending
4086         // commitment_updates when we disconnect.
4087         let chanmon_cfgs = create_chanmon_cfgs(2);
4088         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4089         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4090         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4091         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4092
4093         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4094
4095         // Now try to send a second payment which will fail to send
4096         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4097         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4098         check_added_monitors!(nodes[0], 1);
4099
4100         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4101         assert_eq!(events_1.len(), 1);
4102         match events_1[0] {
4103                 MessageSendEvent::UpdateHTLCs { .. } => {},
4104                 _ => panic!("Unexpected event"),
4105         }
4106
4107         nodes[1].node.claim_funds(payment_preimage_1);
4108         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4109         check_added_monitors!(nodes[1], 1);
4110
4111         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4112         assert_eq!(events_2.len(), 1);
4113         match events_2[0] {
4114                 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 } } => {
4115                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4116                         assert!(update_add_htlcs.is_empty());
4117                         assert_eq!(update_fulfill_htlcs.len(), 1);
4118                         assert!(update_fail_htlcs.is_empty());
4119                         assert!(update_fail_malformed_htlcs.is_empty());
4120                         assert!(update_fee.is_none());
4121
4122                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4123                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4124                         assert_eq!(events_3.len(), 1);
4125                         match events_3[0] {
4126                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4127                                         assert_eq!(*payment_preimage, payment_preimage_1);
4128                                         assert_eq!(*payment_hash, payment_hash_1);
4129                                 },
4130                                 _ => panic!("Unexpected event"),
4131                         }
4132
4133                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4134                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4135                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4136                         check_added_monitors!(nodes[0], 1);
4137                 },
4138                 _ => panic!("Unexpected event"),
4139         }
4140
4141         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4142         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4143
4144         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4145         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4146         assert_eq!(reestablish_1.len(), 1);
4147         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4148         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4149         assert_eq!(reestablish_2.len(), 1);
4150
4151         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4152         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4153         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4154         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4155
4156         assert!(as_resp.0.is_none());
4157         assert!(bs_resp.0.is_none());
4158
4159         assert!(bs_resp.1.is_none());
4160         assert!(bs_resp.2.is_none());
4161
4162         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4163
4164         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4165         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4166         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4167         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4168         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4169         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4170         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4171         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4172         // No commitment_signed so get_event_msg's assert(len == 1) passes
4173         check_added_monitors!(nodes[1], 1);
4174
4175         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4176         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4177         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4178         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4179         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4180         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4181         assert!(bs_second_commitment_signed.update_fee.is_none());
4182         check_added_monitors!(nodes[1], 1);
4183
4184         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4185         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4186         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4187         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4188         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4189         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4190         assert!(as_commitment_signed.update_fee.is_none());
4191         check_added_monitors!(nodes[0], 1);
4192
4193         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4194         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4195         // No commitment_signed so get_event_msg's assert(len == 1) passes
4196         check_added_monitors!(nodes[0], 1);
4197
4198         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4199         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4200         // No commitment_signed so get_event_msg's assert(len == 1) passes
4201         check_added_monitors!(nodes[1], 1);
4202
4203         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4204         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4205         check_added_monitors!(nodes[1], 1);
4206
4207         expect_pending_htlcs_forwardable!(nodes[1]);
4208
4209         let events_5 = nodes[1].node.get_and_clear_pending_events();
4210         assert_eq!(events_5.len(), 1);
4211         match events_5[0] {
4212                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4213                         assert_eq!(payment_hash_2, *payment_hash);
4214                         match &purpose {
4215                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4216                                         assert!(payment_preimage.is_none());
4217                                         assert_eq!(payment_secret_2, *payment_secret);
4218                                 },
4219                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4220                         }
4221                 },
4222                 _ => panic!("Unexpected event"),
4223         }
4224
4225         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4226         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4227         check_added_monitors!(nodes[0], 1);
4228
4229         expect_payment_path_successful!(nodes[0]);
4230         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4231 }
4232
4233 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4234         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4235         // to avoid our counterparty failing the channel.
4236         let chanmon_cfgs = create_chanmon_cfgs(2);
4237         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4238         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4239         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4240
4241         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4242
4243         let our_payment_hash = if send_partial_mpp {
4244                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4245                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4246                 // indicates there are more HTLCs coming.
4247                 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.
4248                 let payment_id = PaymentId([42; 32]);
4249                 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();
4250                 check_added_monitors!(nodes[0], 1);
4251                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4252                 assert_eq!(events.len(), 1);
4253                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4254                 // hop should *not* yet generate any PaymentReceived event(s).
4255                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4256                 our_payment_hash
4257         } else {
4258                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4259         };
4260
4261         let mut block = Block {
4262                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4263                 txdata: vec![],
4264         };
4265         connect_block(&nodes[0], &block);
4266         connect_block(&nodes[1], &block);
4267         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4268         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4269                 block.header.prev_blockhash = block.block_hash();
4270                 connect_block(&nodes[0], &block);
4271                 connect_block(&nodes[1], &block);
4272         }
4273
4274         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4275
4276         check_added_monitors!(nodes[1], 1);
4277         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4278         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4279         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4280         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4281         assert!(htlc_timeout_updates.update_fee.is_none());
4282
4283         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4284         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4285         // 100_000 msat as u64, followed by the height at which we failed back above
4286         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4287         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4288         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4289 }
4290
4291 #[test]
4292 fn test_htlc_timeout() {
4293         do_test_htlc_timeout(true);
4294         do_test_htlc_timeout(false);
4295 }
4296
4297 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4298         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4299         let chanmon_cfgs = create_chanmon_cfgs(3);
4300         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4301         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4302         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4303         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4304         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4305
4306         // Make sure all nodes are at the same starting height
4307         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4308         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4309         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4310
4311         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4312         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4313         {
4314                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4315         }
4316         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4317         check_added_monitors!(nodes[1], 1);
4318
4319         // Now attempt to route a second payment, which should be placed in the holding cell
4320         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4321         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4322         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4323         if forwarded_htlc {
4324                 check_added_monitors!(nodes[0], 1);
4325                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4326                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4327                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4328                 expect_pending_htlcs_forwardable!(nodes[1]);
4329         }
4330         check_added_monitors!(nodes[1], 0);
4331
4332         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4333         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4334         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4335         connect_blocks(&nodes[1], 1);
4336
4337         if forwarded_htlc {
4338                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
4339                 check_added_monitors!(nodes[1], 1);
4340                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4341                 assert_eq!(fail_commit.len(), 1);
4342                 match fail_commit[0] {
4343                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4344                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4345                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4346                         },
4347                         _ => unreachable!(),
4348                 }
4349                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4350         } else {
4351                 let events = nodes[1].node.get_and_clear_pending_events();
4352                 assert_eq!(events.len(), 2);
4353                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4354                         assert_eq!(*payment_hash, second_payment_hash);
4355                 } else { panic!("Unexpected event"); }
4356                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4357                         assert_eq!(*payment_hash, second_payment_hash);
4358                 } else { panic!("Unexpected event"); }
4359         }
4360 }
4361
4362 #[test]
4363 fn test_holding_cell_htlc_add_timeouts() {
4364         do_test_holding_cell_htlc_add_timeouts(false);
4365         do_test_holding_cell_htlc_add_timeouts(true);
4366 }
4367
4368 #[test]
4369 fn test_no_txn_manager_serialize_deserialize() {
4370         let chanmon_cfgs = create_chanmon_cfgs(2);
4371         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4372         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4373         let logger: test_utils::TestLogger;
4374         let fee_estimator: test_utils::TestFeeEstimator;
4375         let persister: test_utils::TestPersister;
4376         let new_chain_monitor: test_utils::TestChainMonitor;
4377         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4378         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4379
4380         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4381
4382         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4383
4384         let nodes_0_serialized = nodes[0].node.encode();
4385         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4386         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4387                 .write(&mut chan_0_monitor_serialized).unwrap();
4388
4389         logger = test_utils::TestLogger::new();
4390         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4391         persister = test_utils::TestPersister::new();
4392         let keys_manager = &chanmon_cfgs[0].keys_manager;
4393         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4394         nodes[0].chain_monitor = &new_chain_monitor;
4395         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4396         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4397                 &mut chan_0_monitor_read, keys_manager).unwrap();
4398         assert!(chan_0_monitor_read.is_empty());
4399
4400         let mut nodes_0_read = &nodes_0_serialized[..];
4401         let config = UserConfig::default();
4402         let (_, nodes_0_deserialized_tmp) = {
4403                 let mut channel_monitors = HashMap::new();
4404                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4405                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4406                         default_config: config,
4407                         keys_manager,
4408                         fee_estimator: &fee_estimator,
4409                         chain_monitor: nodes[0].chain_monitor,
4410                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4411                         logger: &logger,
4412                         channel_monitors,
4413                 }).unwrap()
4414         };
4415         nodes_0_deserialized = nodes_0_deserialized_tmp;
4416         assert!(nodes_0_read.is_empty());
4417
4418         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4419         nodes[0].node = &nodes_0_deserialized;
4420         assert_eq!(nodes[0].node.list_channels().len(), 1);
4421         check_added_monitors!(nodes[0], 1);
4422
4423         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4424         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4425         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4426         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4427
4428         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4429         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4430         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4431         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4432
4433         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4434         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4435         for node in nodes.iter() {
4436                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4437                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4438                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4439         }
4440
4441         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4442 }
4443
4444 #[test]
4445 fn test_manager_serialize_deserialize_events() {
4446         // This test makes sure the events field in ChannelManager survives de/serialization
4447         let chanmon_cfgs = create_chanmon_cfgs(2);
4448         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4449         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4450         let fee_estimator: test_utils::TestFeeEstimator;
4451         let persister: test_utils::TestPersister;
4452         let logger: test_utils::TestLogger;
4453         let new_chain_monitor: test_utils::TestChainMonitor;
4454         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4455         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4456
4457         // Start creating a channel, but stop right before broadcasting the funding transaction
4458         let channel_value = 100000;
4459         let push_msat = 10001;
4460         let a_flags = InitFeatures::known();
4461         let b_flags = InitFeatures::known();
4462         let node_a = nodes.remove(0);
4463         let node_b = nodes.remove(0);
4464         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4465         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()));
4466         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()));
4467
4468         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4469
4470         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4471         check_added_monitors!(node_a, 0);
4472
4473         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()));
4474         {
4475                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4476                 assert_eq!(added_monitors.len(), 1);
4477                 assert_eq!(added_monitors[0].0, funding_output);
4478                 added_monitors.clear();
4479         }
4480
4481         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4482         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4483         {
4484                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4485                 assert_eq!(added_monitors.len(), 1);
4486                 assert_eq!(added_monitors[0].0, funding_output);
4487                 added_monitors.clear();
4488         }
4489         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4490
4491         nodes.push(node_a);
4492         nodes.push(node_b);
4493
4494         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4495         let nodes_0_serialized = nodes[0].node.encode();
4496         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4497         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4498
4499         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4500         logger = test_utils::TestLogger::new();
4501         persister = test_utils::TestPersister::new();
4502         let keys_manager = &chanmon_cfgs[0].keys_manager;
4503         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4504         nodes[0].chain_monitor = &new_chain_monitor;
4505         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4506         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4507                 &mut chan_0_monitor_read, keys_manager).unwrap();
4508         assert!(chan_0_monitor_read.is_empty());
4509
4510         let mut nodes_0_read = &nodes_0_serialized[..];
4511         let config = UserConfig::default();
4512         let (_, nodes_0_deserialized_tmp) = {
4513                 let mut channel_monitors = HashMap::new();
4514                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4515                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4516                         default_config: config,
4517                         keys_manager,
4518                         fee_estimator: &fee_estimator,
4519                         chain_monitor: nodes[0].chain_monitor,
4520                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4521                         logger: &logger,
4522                         channel_monitors,
4523                 }).unwrap()
4524         };
4525         nodes_0_deserialized = nodes_0_deserialized_tmp;
4526         assert!(nodes_0_read.is_empty());
4527
4528         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4529
4530         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4531         nodes[0].node = &nodes_0_deserialized;
4532
4533         // After deserializing, make sure the funding_transaction is still held by the channel manager
4534         let events_4 = nodes[0].node.get_and_clear_pending_events();
4535         assert_eq!(events_4.len(), 0);
4536         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4537         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4538
4539         // Make sure the channel is functioning as though the de/serialization never happened
4540         assert_eq!(nodes[0].node.list_channels().len(), 1);
4541         check_added_monitors!(nodes[0], 1);
4542
4543         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4544         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4545         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4546         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4547
4548         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4549         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4550         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4551         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4552
4553         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4554         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4555         for node in nodes.iter() {
4556                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4557                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4558                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4559         }
4560
4561         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4562 }
4563
4564 #[test]
4565 fn test_simple_manager_serialize_deserialize() {
4566         let chanmon_cfgs = create_chanmon_cfgs(2);
4567         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4568         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4569         let logger: test_utils::TestLogger;
4570         let fee_estimator: test_utils::TestFeeEstimator;
4571         let persister: test_utils::TestPersister;
4572         let new_chain_monitor: test_utils::TestChainMonitor;
4573         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4574         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4575         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4576
4577         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4578         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4579
4580         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4581
4582         let nodes_0_serialized = nodes[0].node.encode();
4583         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4584         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4585
4586         logger = test_utils::TestLogger::new();
4587         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4588         persister = test_utils::TestPersister::new();
4589         let keys_manager = &chanmon_cfgs[0].keys_manager;
4590         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4591         nodes[0].chain_monitor = &new_chain_monitor;
4592         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4593         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4594                 &mut chan_0_monitor_read, keys_manager).unwrap();
4595         assert!(chan_0_monitor_read.is_empty());
4596
4597         let mut nodes_0_read = &nodes_0_serialized[..];
4598         let (_, nodes_0_deserialized_tmp) = {
4599                 let mut channel_monitors = HashMap::new();
4600                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4601                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4602                         default_config: UserConfig::default(),
4603                         keys_manager,
4604                         fee_estimator: &fee_estimator,
4605                         chain_monitor: nodes[0].chain_monitor,
4606                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4607                         logger: &logger,
4608                         channel_monitors,
4609                 }).unwrap()
4610         };
4611         nodes_0_deserialized = nodes_0_deserialized_tmp;
4612         assert!(nodes_0_read.is_empty());
4613
4614         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4615         nodes[0].node = &nodes_0_deserialized;
4616         check_added_monitors!(nodes[0], 1);
4617
4618         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4619
4620         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4621         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4622 }
4623
4624 #[test]
4625 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4626         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4627         let chanmon_cfgs = create_chanmon_cfgs(4);
4628         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4629         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4630         let logger: test_utils::TestLogger;
4631         let fee_estimator: test_utils::TestFeeEstimator;
4632         let persister: test_utils::TestPersister;
4633         let new_chain_monitor: test_utils::TestChainMonitor;
4634         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4635         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4636         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4637         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4638         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4639
4640         let mut node_0_stale_monitors_serialized = Vec::new();
4641         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4642                 let mut writer = test_utils::TestVecWriter(Vec::new());
4643                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4644                 node_0_stale_monitors_serialized.push(writer.0);
4645         }
4646
4647         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4648
4649         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4650         let nodes_0_serialized = nodes[0].node.encode();
4651
4652         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4653         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4654         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4655         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4656
4657         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4658         // nodes[3])
4659         let mut node_0_monitors_serialized = Vec::new();
4660         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4661                 let mut writer = test_utils::TestVecWriter(Vec::new());
4662                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4663                 node_0_monitors_serialized.push(writer.0);
4664         }
4665
4666         logger = test_utils::TestLogger::new();
4667         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4668         persister = test_utils::TestPersister::new();
4669         let keys_manager = &chanmon_cfgs[0].keys_manager;
4670         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4671         nodes[0].chain_monitor = &new_chain_monitor;
4672
4673
4674         let mut node_0_stale_monitors = Vec::new();
4675         for serialized in node_0_stale_monitors_serialized.iter() {
4676                 let mut read = &serialized[..];
4677                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4678                 assert!(read.is_empty());
4679                 node_0_stale_monitors.push(monitor);
4680         }
4681
4682         let mut node_0_monitors = Vec::new();
4683         for serialized in node_0_monitors_serialized.iter() {
4684                 let mut read = &serialized[..];
4685                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4686                 assert!(read.is_empty());
4687                 node_0_monitors.push(monitor);
4688         }
4689
4690         let mut nodes_0_read = &nodes_0_serialized[..];
4691         if let Err(msgs::DecodeError::InvalidValue) =
4692                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4693                 default_config: UserConfig::default(),
4694                 keys_manager,
4695                 fee_estimator: &fee_estimator,
4696                 chain_monitor: nodes[0].chain_monitor,
4697                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4698                 logger: &logger,
4699                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4700         }) { } else {
4701                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4702         };
4703
4704         let mut nodes_0_read = &nodes_0_serialized[..];
4705         let (_, nodes_0_deserialized_tmp) =
4706                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4707                 default_config: UserConfig::default(),
4708                 keys_manager,
4709                 fee_estimator: &fee_estimator,
4710                 chain_monitor: nodes[0].chain_monitor,
4711                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4712                 logger: &logger,
4713                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4714         }).unwrap();
4715         nodes_0_deserialized = nodes_0_deserialized_tmp;
4716         assert!(nodes_0_read.is_empty());
4717
4718         { // Channel close should result in a commitment tx
4719                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4720                 assert_eq!(txn.len(), 1);
4721                 check_spends!(txn[0], funding_tx);
4722                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4723         }
4724
4725         for monitor in node_0_monitors.drain(..) {
4726                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4727                 check_added_monitors!(nodes[0], 1);
4728         }
4729         nodes[0].node = &nodes_0_deserialized;
4730         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4731
4732         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4733         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4734         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4735         //... and we can even still claim the payment!
4736         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4737
4738         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4739         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4740         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4741         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4742         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4743         assert_eq!(msg_events.len(), 1);
4744         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4745                 match action {
4746                         &ErrorAction::SendErrorMessage { ref msg } => {
4747                                 assert_eq!(msg.channel_id, channel_id);
4748                         },
4749                         _ => panic!("Unexpected event!"),
4750                 }
4751         }
4752 }
4753
4754 macro_rules! check_spendable_outputs {
4755         ($node: expr, $keysinterface: expr) => {
4756                 {
4757                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4758                         let mut txn = Vec::new();
4759                         let mut all_outputs = Vec::new();
4760                         let secp_ctx = Secp256k1::new();
4761                         for event in events.drain(..) {
4762                                 match event {
4763                                         Event::SpendableOutputs { mut outputs } => {
4764                                                 for outp in outputs.drain(..) {
4765                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4766                                                         all_outputs.push(outp);
4767                                                 }
4768                                         },
4769                                         _ => panic!("Unexpected event"),
4770                                 };
4771                         }
4772                         if all_outputs.len() > 1 {
4773                                 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) {
4774                                         txn.push(tx);
4775                                 }
4776                         }
4777                         txn
4778                 }
4779         }
4780 }
4781
4782 #[test]
4783 fn test_claim_sizeable_push_msat() {
4784         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4785         let chanmon_cfgs = create_chanmon_cfgs(2);
4786         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4787         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4788         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4789
4790         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4791         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4792         check_closed_broadcast!(nodes[1], true);
4793         check_added_monitors!(nodes[1], 1);
4794         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4795         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4796         assert_eq!(node_txn.len(), 1);
4797         check_spends!(node_txn[0], chan.3);
4798         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
4799
4800         mine_transaction(&nodes[1], &node_txn[0]);
4801         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4802
4803         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4804         assert_eq!(spend_txn.len(), 1);
4805         assert_eq!(spend_txn[0].input.len(), 1);
4806         check_spends!(spend_txn[0], node_txn[0]);
4807         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4808 }
4809
4810 #[test]
4811 fn test_claim_on_remote_sizeable_push_msat() {
4812         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4813         // to_remote output is encumbered by a P2WPKH
4814         let chanmon_cfgs = create_chanmon_cfgs(2);
4815         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4816         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4817         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4818
4819         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4820         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4821         check_closed_broadcast!(nodes[0], true);
4822         check_added_monitors!(nodes[0], 1);
4823         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4824
4825         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4826         assert_eq!(node_txn.len(), 1);
4827         check_spends!(node_txn[0], chan.3);
4828         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
4829
4830         mine_transaction(&nodes[1], &node_txn[0]);
4831         check_closed_broadcast!(nodes[1], true);
4832         check_added_monitors!(nodes[1], 1);
4833         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4834         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4835
4836         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4837         assert_eq!(spend_txn.len(), 1);
4838         check_spends!(spend_txn[0], node_txn[0]);
4839 }
4840
4841 #[test]
4842 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4843         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4844         // to_remote output is encumbered by a P2WPKH
4845
4846         let chanmon_cfgs = create_chanmon_cfgs(2);
4847         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4848         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4849         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4850
4851         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4852         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4853         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4854         assert_eq!(revoked_local_txn[0].input.len(), 1);
4855         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4856
4857         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4858         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4859         check_closed_broadcast!(nodes[1], true);
4860         check_added_monitors!(nodes[1], 1);
4861         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4862
4863         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4864         mine_transaction(&nodes[1], &node_txn[0]);
4865         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4866
4867         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4868         assert_eq!(spend_txn.len(), 3);
4869         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4870         check_spends!(spend_txn[1], node_txn[0]);
4871         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4872 }
4873
4874 #[test]
4875 fn test_static_spendable_outputs_preimage_tx() {
4876         let chanmon_cfgs = create_chanmon_cfgs(2);
4877         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4878         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4879         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4880
4881         // Create some initial channels
4882         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4883
4884         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4885
4886         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4887         assert_eq!(commitment_tx[0].input.len(), 1);
4888         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4889
4890         // Settle A's commitment tx on B's chain
4891         nodes[1].node.claim_funds(payment_preimage);
4892         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4893         check_added_monitors!(nodes[1], 1);
4894         mine_transaction(&nodes[1], &commitment_tx[0]);
4895         check_added_monitors!(nodes[1], 1);
4896         let events = nodes[1].node.get_and_clear_pending_msg_events();
4897         match events[0] {
4898                 MessageSendEvent::UpdateHTLCs { .. } => {},
4899                 _ => panic!("Unexpected event"),
4900         }
4901         match events[1] {
4902                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4903                 _ => panic!("Unexepected event"),
4904         }
4905
4906         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4907         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4908         assert_eq!(node_txn.len(), 3);
4909         check_spends!(node_txn[0], commitment_tx[0]);
4910         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4911         check_spends!(node_txn[1], chan_1.3);
4912         check_spends!(node_txn[2], node_txn[1]);
4913
4914         mine_transaction(&nodes[1], &node_txn[0]);
4915         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4916         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4917
4918         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4919         assert_eq!(spend_txn.len(), 1);
4920         check_spends!(spend_txn[0], node_txn[0]);
4921 }
4922
4923 #[test]
4924 fn test_static_spendable_outputs_timeout_tx() {
4925         let chanmon_cfgs = create_chanmon_cfgs(2);
4926         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4927         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4928         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4929
4930         // Create some initial channels
4931         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4932
4933         // Rebalance the network a bit by relaying one payment through all the channels ...
4934         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4935
4936         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4937
4938         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4939         assert_eq!(commitment_tx[0].input.len(), 1);
4940         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4941
4942         // Settle A's commitment tx on B' chain
4943         mine_transaction(&nodes[1], &commitment_tx[0]);
4944         check_added_monitors!(nodes[1], 1);
4945         let events = nodes[1].node.get_and_clear_pending_msg_events();
4946         match events[0] {
4947                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4948                 _ => panic!("Unexpected event"),
4949         }
4950         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4951
4952         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4953         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4954         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4955         check_spends!(node_txn[0], chan_1.3.clone());
4956         check_spends!(node_txn[1],  commitment_tx[0].clone());
4957         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4958
4959         mine_transaction(&nodes[1], &node_txn[1]);
4960         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4961         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4962         expect_payment_failed!(nodes[1], our_payment_hash, true);
4963
4964         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4965         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4966         check_spends!(spend_txn[0], commitment_tx[0]);
4967         check_spends!(spend_txn[1], node_txn[1]);
4968         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4969 }
4970
4971 #[test]
4972 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4973         let chanmon_cfgs = create_chanmon_cfgs(2);
4974         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4975         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4976         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4977
4978         // Create some initial channels
4979         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4980
4981         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4982         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4983         assert_eq!(revoked_local_txn[0].input.len(), 1);
4984         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4985
4986         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4987
4988         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4989         check_closed_broadcast!(nodes[1], true);
4990         check_added_monitors!(nodes[1], 1);
4991         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4992
4993         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4994         assert_eq!(node_txn.len(), 2);
4995         assert_eq!(node_txn[0].input.len(), 2);
4996         check_spends!(node_txn[0], revoked_local_txn[0]);
4997
4998         mine_transaction(&nodes[1], &node_txn[0]);
4999         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5000
5001         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5002         assert_eq!(spend_txn.len(), 1);
5003         check_spends!(spend_txn[0], node_txn[0]);
5004 }
5005
5006 #[test]
5007 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5008         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5009         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5010         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5011         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5012         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5013
5014         // Create some initial channels
5015         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5016
5017         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5018         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5019         assert_eq!(revoked_local_txn[0].input.len(), 1);
5020         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5021
5022         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5023
5024         // A will generate HTLC-Timeout from revoked commitment tx
5025         mine_transaction(&nodes[0], &revoked_local_txn[0]);
5026         check_closed_broadcast!(nodes[0], true);
5027         check_added_monitors!(nodes[0], 1);
5028         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5029         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5030
5031         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
5032         assert_eq!(revoked_htlc_txn.len(), 2);
5033         check_spends!(revoked_htlc_txn[0], chan_1.3);
5034         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5035         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5036         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5037         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5038
5039         // B will generate justice tx from A's revoked commitment/HTLC tx
5040         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5041         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5042         check_closed_broadcast!(nodes[1], true);
5043         check_added_monitors!(nodes[1], 1);
5044         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5045
5046         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5047         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5048         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5049         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5050         // transactions next...
5051         assert_eq!(node_txn[0].input.len(), 3);
5052         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5053
5054         assert_eq!(node_txn[1].input.len(), 2);
5055         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5056         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5057                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5058         } else {
5059                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5060                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5061         }
5062
5063         assert_eq!(node_txn[2].input.len(), 1);
5064         check_spends!(node_txn[2], chan_1.3);
5065
5066         mine_transaction(&nodes[1], &node_txn[1]);
5067         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5068
5069         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5070         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5071         assert_eq!(spend_txn.len(), 1);
5072         assert_eq!(spend_txn[0].input.len(), 1);
5073         check_spends!(spend_txn[0], node_txn[1]);
5074 }
5075
5076 #[test]
5077 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5078         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5079         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5080         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5081         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5082         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5083
5084         // Create some initial channels
5085         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5086
5087         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5088         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5089         assert_eq!(revoked_local_txn[0].input.len(), 1);
5090         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5091
5092         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5093         assert_eq!(revoked_local_txn[0].output.len(), 2);
5094
5095         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5096
5097         // B will generate HTLC-Success from revoked commitment tx
5098         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5099         check_closed_broadcast!(nodes[1], true);
5100         check_added_monitors!(nodes[1], 1);
5101         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5102         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5103
5104         assert_eq!(revoked_htlc_txn.len(), 2);
5105         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5106         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5107         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5108
5109         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5110         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5111         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5112
5113         // A will generate justice tx from B's revoked commitment/HTLC tx
5114         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5115         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5116         check_closed_broadcast!(nodes[0], true);
5117         check_added_monitors!(nodes[0], 1);
5118         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5119
5120         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5121         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5122
5123         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5124         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5125         // transactions next...
5126         assert_eq!(node_txn[0].input.len(), 2);
5127         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5128         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5129                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5130         } else {
5131                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5132                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5133         }
5134
5135         assert_eq!(node_txn[1].input.len(), 1);
5136         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5137
5138         check_spends!(node_txn[2], chan_1.3);
5139
5140         mine_transaction(&nodes[0], &node_txn[1]);
5141         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5142
5143         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5144         // didn't try to generate any new transactions.
5145
5146         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5147         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5148         assert_eq!(spend_txn.len(), 3);
5149         assert_eq!(spend_txn[0].input.len(), 1);
5150         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5151         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5152         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5153         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5154 }
5155
5156 #[test]
5157 fn test_onchain_to_onchain_claim() {
5158         // Test that in case of channel closure, we detect the state of output and claim HTLC
5159         // on downstream peer's remote commitment tx.
5160         // First, have C claim an HTLC against its own latest commitment transaction.
5161         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5162         // channel.
5163         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5164         // gets broadcast.
5165
5166         let chanmon_cfgs = create_chanmon_cfgs(3);
5167         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5168         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5169         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5170
5171         // Create some initial channels
5172         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5173         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5174
5175         // Ensure all nodes are at the same height
5176         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5177         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5178         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5179         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5180
5181         // Rebalance the network a bit by relaying one payment through all the channels ...
5182         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5183         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5184
5185         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5186         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5187         check_spends!(commitment_tx[0], chan_2.3);
5188         nodes[2].node.claim_funds(payment_preimage);
5189         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5190         check_added_monitors!(nodes[2], 1);
5191         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5192         assert!(updates.update_add_htlcs.is_empty());
5193         assert!(updates.update_fail_htlcs.is_empty());
5194         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5195         assert!(updates.update_fail_malformed_htlcs.is_empty());
5196
5197         mine_transaction(&nodes[2], &commitment_tx[0]);
5198         check_closed_broadcast!(nodes[2], true);
5199         check_added_monitors!(nodes[2], 1);
5200         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5201
5202         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5203         assert_eq!(c_txn.len(), 3);
5204         assert_eq!(c_txn[0], c_txn[2]);
5205         assert_eq!(commitment_tx[0], c_txn[1]);
5206         check_spends!(c_txn[1], chan_2.3);
5207         check_spends!(c_txn[2], c_txn[1]);
5208         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5209         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5210         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5211         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5212
5213         // 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
5214         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5215         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5216         check_added_monitors!(nodes[1], 1);
5217         let events = nodes[1].node.get_and_clear_pending_events();
5218         assert_eq!(events.len(), 2);
5219         match events[0] {
5220                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5221                 _ => panic!("Unexpected event"),
5222         }
5223         match events[1] {
5224                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5225                         assert_eq!(fee_earned_msat, Some(1000));
5226                         assert_eq!(prev_channel_id, Some(chan_1.2));
5227                         assert_eq!(claim_from_onchain_tx, true);
5228                         assert_eq!(next_channel_id, Some(chan_2.2));
5229                 },
5230                 _ => panic!("Unexpected event"),
5231         }
5232         {
5233                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5234                 // ChannelMonitor: claim tx
5235                 assert_eq!(b_txn.len(), 1);
5236                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5237                 b_txn.clear();
5238         }
5239         check_added_monitors!(nodes[1], 1);
5240         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5241         assert_eq!(msg_events.len(), 3);
5242         match msg_events[0] {
5243                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5244                 _ => panic!("Unexpected event"),
5245         }
5246         match msg_events[1] {
5247                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5248                 _ => panic!("Unexpected event"),
5249         }
5250         match msg_events[2] {
5251                 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, .. } } => {
5252                         assert!(update_add_htlcs.is_empty());
5253                         assert!(update_fail_htlcs.is_empty());
5254                         assert_eq!(update_fulfill_htlcs.len(), 1);
5255                         assert!(update_fail_malformed_htlcs.is_empty());
5256                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5257                 },
5258                 _ => panic!("Unexpected event"),
5259         };
5260         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5261         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5262         mine_transaction(&nodes[1], &commitment_tx[0]);
5263         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5264         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5265         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5266         assert_eq!(b_txn.len(), 3);
5267         check_spends!(b_txn[1], chan_1.3);
5268         check_spends!(b_txn[2], b_txn[1]);
5269         check_spends!(b_txn[0], commitment_tx[0]);
5270         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5271         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5272         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5273
5274         check_closed_broadcast!(nodes[1], true);
5275         check_added_monitors!(nodes[1], 1);
5276 }
5277
5278 #[test]
5279 fn test_duplicate_payment_hash_one_failure_one_success() {
5280         // Topology : A --> B --> C --> D
5281         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5282         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5283         // we forward one of the payments onwards to D.
5284         let chanmon_cfgs = create_chanmon_cfgs(4);
5285         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5286         // When this test was written, the default base fee floated based on the HTLC count.
5287         // It is now fixed, so we simply set the fee to the expected value here.
5288         let mut config = test_default_channel_config();
5289         config.channel_config.forwarding_fee_base_msat = 196;
5290         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5291                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5292         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5293
5294         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5295         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5296         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5297
5298         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5299         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5300         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5301         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5302         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5303
5304         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5305
5306         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5307         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5308         // script push size limit so that the below script length checks match
5309         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5310         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5311                 .with_features(InvoiceFeatures::known());
5312         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5313         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5314
5315         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5316         assert_eq!(commitment_txn[0].input.len(), 1);
5317         check_spends!(commitment_txn[0], chan_2.3);
5318
5319         mine_transaction(&nodes[1], &commitment_txn[0]);
5320         check_closed_broadcast!(nodes[1], true);
5321         check_added_monitors!(nodes[1], 1);
5322         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5323         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5324
5325         let htlc_timeout_tx;
5326         { // Extract one of the two HTLC-Timeout transaction
5327                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5328                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5329                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5330                 check_spends!(node_txn[0], chan_2.3);
5331
5332                 check_spends!(node_txn[1], commitment_txn[0]);
5333                 assert_eq!(node_txn[1].input.len(), 1);
5334
5335                 if node_txn.len() > 3 {
5336                         check_spends!(node_txn[2], commitment_txn[0]);
5337                         assert_eq!(node_txn[2].input.len(), 1);
5338                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5339
5340                         check_spends!(node_txn[3], commitment_txn[0]);
5341                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5342                 } else {
5343                         check_spends!(node_txn[2], commitment_txn[0]);
5344                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5345                 }
5346
5347                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5348                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5349                 if node_txn.len() > 3 {
5350                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5351                 }
5352                 htlc_timeout_tx = node_txn[1].clone();
5353         }
5354
5355         nodes[2].node.claim_funds(our_payment_preimage);
5356         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5357
5358         mine_transaction(&nodes[2], &commitment_txn[0]);
5359         check_added_monitors!(nodes[2], 2);
5360         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5361         let events = nodes[2].node.get_and_clear_pending_msg_events();
5362         match events[0] {
5363                 MessageSendEvent::UpdateHTLCs { .. } => {},
5364                 _ => panic!("Unexpected event"),
5365         }
5366         match events[1] {
5367                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5368                 _ => panic!("Unexepected event"),
5369         }
5370         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5371         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)
5372         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5373         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5374         assert_eq!(htlc_success_txn[0].input.len(), 1);
5375         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5376         assert_eq!(htlc_success_txn[1].input.len(), 1);
5377         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5378         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5379         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5380         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5381         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5382         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5383
5384         mine_transaction(&nodes[1], &htlc_timeout_tx);
5385         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5386         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
5387         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5388         assert!(htlc_updates.update_add_htlcs.is_empty());
5389         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5390         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5391         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5392         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5393         check_added_monitors!(nodes[1], 1);
5394
5395         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5396         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5397         {
5398                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5399         }
5400         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5401
5402         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5403         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5404         // and nodes[2] fee) is rounded down and then claimed in full.
5405         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5406         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5407         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5408         assert!(updates.update_add_htlcs.is_empty());
5409         assert!(updates.update_fail_htlcs.is_empty());
5410         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5411         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5412         assert!(updates.update_fail_malformed_htlcs.is_empty());
5413         check_added_monitors!(nodes[1], 1);
5414
5415         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5416         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5417
5418         let events = nodes[0].node.get_and_clear_pending_events();
5419         match events[0] {
5420                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5421                         assert_eq!(*payment_preimage, our_payment_preimage);
5422                         assert_eq!(*payment_hash, duplicate_payment_hash);
5423                 }
5424                 _ => panic!("Unexpected event"),
5425         }
5426 }
5427
5428 #[test]
5429 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5430         let chanmon_cfgs = create_chanmon_cfgs(2);
5431         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5432         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5433         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5434
5435         // Create some initial channels
5436         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5437
5438         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5439         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5440         assert_eq!(local_txn.len(), 1);
5441         assert_eq!(local_txn[0].input.len(), 1);
5442         check_spends!(local_txn[0], chan_1.3);
5443
5444         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5445         nodes[1].node.claim_funds(payment_preimage);
5446         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5447         check_added_monitors!(nodes[1], 1);
5448
5449         mine_transaction(&nodes[1], &local_txn[0]);
5450         check_added_monitors!(nodes[1], 1);
5451         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5452         let events = nodes[1].node.get_and_clear_pending_msg_events();
5453         match events[0] {
5454                 MessageSendEvent::UpdateHTLCs { .. } => {},
5455                 _ => panic!("Unexpected event"),
5456         }
5457         match events[1] {
5458                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5459                 _ => panic!("Unexepected event"),
5460         }
5461         let node_tx = {
5462                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5463                 assert_eq!(node_txn.len(), 3);
5464                 assert_eq!(node_txn[0], node_txn[2]);
5465                 assert_eq!(node_txn[1], local_txn[0]);
5466                 assert_eq!(node_txn[0].input.len(), 1);
5467                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5468                 check_spends!(node_txn[0], local_txn[0]);
5469                 node_txn[0].clone()
5470         };
5471
5472         mine_transaction(&nodes[1], &node_tx);
5473         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5474
5475         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5476         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5477         assert_eq!(spend_txn.len(), 1);
5478         assert_eq!(spend_txn[0].input.len(), 1);
5479         check_spends!(spend_txn[0], node_tx);
5480         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5481 }
5482
5483 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5484         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5485         // unrevoked commitment transaction.
5486         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5487         // a remote RAA before they could be failed backwards (and combinations thereof).
5488         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5489         // use the same payment hashes.
5490         // Thus, we use a six-node network:
5491         //
5492         // A \         / E
5493         //    - C - D -
5494         // B /         \ F
5495         // And test where C fails back to A/B when D announces its latest commitment transaction
5496         let chanmon_cfgs = create_chanmon_cfgs(6);
5497         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5498         // When this test was written, the default base fee floated based on the HTLC count.
5499         // It is now fixed, so we simply set the fee to the expected value here.
5500         let mut config = test_default_channel_config();
5501         config.channel_config.forwarding_fee_base_msat = 196;
5502         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5503                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5504         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5505
5506         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5507         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5508         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5509         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5510         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5511
5512         // Rebalance and check output sanity...
5513         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5514         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5515         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5516
5517         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
5518         // 0th HTLC:
5519         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
5520         // 1st HTLC:
5521         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
5522         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5523         // 2nd HTLC:
5524         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
5525         // 3rd HTLC:
5526         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
5527         // 4th HTLC:
5528         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5529         // 5th HTLC:
5530         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5531         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5532         // 6th HTLC:
5533         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());
5534         // 7th HTLC:
5535         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());
5536
5537         // 8th HTLC:
5538         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5539         // 9th HTLC:
5540         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5541         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
5542
5543         // 10th HTLC:
5544         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
5545         // 11th HTLC:
5546         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5547         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());
5548
5549         // Double-check that six of the new HTLC were added
5550         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5551         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5552         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5553         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5554
5555         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5556         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5557         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5558         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5559         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5560         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5561         check_added_monitors!(nodes[4], 0);
5562
5563         let failed_destinations = vec![
5564                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5565                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5566                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5567                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5568         ];
5569         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5570         check_added_monitors!(nodes[4], 1);
5571
5572         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5573         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5574         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5575         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5576         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5577         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5578
5579         // Fail 3rd below-dust and 7th above-dust HTLCs
5580         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5581         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5582         check_added_monitors!(nodes[5], 0);
5583
5584         let failed_destinations_2 = vec![
5585                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5586                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5587         ];
5588         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5589         check_added_monitors!(nodes[5], 1);
5590
5591         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5592         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5593         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5594         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5595
5596         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5597
5598         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5599         let failed_destinations_3 = vec![
5600                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5601                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5602                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5603                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5604                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5605                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5606         ];
5607         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5608         check_added_monitors!(nodes[3], 1);
5609         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5610         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5611         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5612         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5613         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5614         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5615         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5616         if deliver_last_raa {
5617                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5618         } else {
5619                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5620         }
5621
5622         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5623         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5624         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5625         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5626         //
5627         // We now broadcast the latest commitment transaction, which *should* result in failures for
5628         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5629         // the non-broadcast above-dust HTLCs.
5630         //
5631         // Alternatively, we may broadcast the previous commitment transaction, which should only
5632         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5633         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5634
5635         if announce_latest {
5636                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5637         } else {
5638                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5639         }
5640         let events = nodes[2].node.get_and_clear_pending_events();
5641         let close_event = if deliver_last_raa {
5642                 assert_eq!(events.len(), 2 + 6);
5643                 events.last().clone().unwrap()
5644         } else {
5645                 assert_eq!(events.len(), 1);
5646                 events.last().clone().unwrap()
5647         };
5648         match close_event {
5649                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5650                 _ => panic!("Unexpected event"),
5651         }
5652
5653         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5654         check_closed_broadcast!(nodes[2], true);
5655         if deliver_last_raa {
5656                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5657
5658                 let expected_destinations: Vec<HTLCDestination> = repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(3).collect();
5659                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5660         } else {
5661                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5662                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5663                 } else {
5664                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5665                 };
5666
5667                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5668         }
5669         check_added_monitors!(nodes[2], 3);
5670
5671         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5672         assert_eq!(cs_msgs.len(), 2);
5673         let mut a_done = false;
5674         for msg in cs_msgs {
5675                 match msg {
5676                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5677                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5678                                 // should be failed-backwards here.
5679                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5680                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5681                                         for htlc in &updates.update_fail_htlcs {
5682                                                 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 });
5683                                         }
5684                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5685                                         assert!(!a_done);
5686                                         a_done = true;
5687                                         &nodes[0]
5688                                 } else {
5689                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5690                                         for htlc in &updates.update_fail_htlcs {
5691                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5692                                         }
5693                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5694                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5695                                         &nodes[1]
5696                                 };
5697                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5698                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5699                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5700                                 if announce_latest {
5701                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5702                                         if *node_id == nodes[0].node.get_our_node_id() {
5703                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5704                                         }
5705                                 }
5706                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5707                         },
5708                         _ => panic!("Unexpected event"),
5709                 }
5710         }
5711
5712         let as_events = nodes[0].node.get_and_clear_pending_events();
5713         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5714         let mut as_failds = HashSet::new();
5715         let mut as_updates = 0;
5716         for event in as_events.iter() {
5717                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5718                         assert!(as_failds.insert(*payment_hash));
5719                         if *payment_hash != payment_hash_2 {
5720                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5721                         } else {
5722                                 assert!(!rejected_by_dest);
5723                         }
5724                         if network_update.is_some() {
5725                                 as_updates += 1;
5726                         }
5727                 } else { panic!("Unexpected event"); }
5728         }
5729         assert!(as_failds.contains(&payment_hash_1));
5730         assert!(as_failds.contains(&payment_hash_2));
5731         if announce_latest {
5732                 assert!(as_failds.contains(&payment_hash_3));
5733                 assert!(as_failds.contains(&payment_hash_5));
5734         }
5735         assert!(as_failds.contains(&payment_hash_6));
5736
5737         let bs_events = nodes[1].node.get_and_clear_pending_events();
5738         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5739         let mut bs_failds = HashSet::new();
5740         let mut bs_updates = 0;
5741         for event in bs_events.iter() {
5742                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5743                         assert!(bs_failds.insert(*payment_hash));
5744                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5745                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5746                         } else {
5747                                 assert!(!rejected_by_dest);
5748                         }
5749                         if network_update.is_some() {
5750                                 bs_updates += 1;
5751                         }
5752                 } else { panic!("Unexpected event"); }
5753         }
5754         assert!(bs_failds.contains(&payment_hash_1));
5755         assert!(bs_failds.contains(&payment_hash_2));
5756         if announce_latest {
5757                 assert!(bs_failds.contains(&payment_hash_4));
5758         }
5759         assert!(bs_failds.contains(&payment_hash_5));
5760
5761         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5762         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5763         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5764         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5765         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5766         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5767 }
5768
5769 #[test]
5770 fn test_fail_backwards_latest_remote_announce_a() {
5771         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5772 }
5773
5774 #[test]
5775 fn test_fail_backwards_latest_remote_announce_b() {
5776         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5777 }
5778
5779 #[test]
5780 fn test_fail_backwards_previous_remote_announce() {
5781         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5782         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5783         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5784 }
5785
5786 #[test]
5787 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5788         let chanmon_cfgs = create_chanmon_cfgs(2);
5789         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5790         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5791         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5792
5793         // Create some initial channels
5794         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5795
5796         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5797         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5798         assert_eq!(local_txn[0].input.len(), 1);
5799         check_spends!(local_txn[0], chan_1.3);
5800
5801         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5802         mine_transaction(&nodes[0], &local_txn[0]);
5803         check_closed_broadcast!(nodes[0], true);
5804         check_added_monitors!(nodes[0], 1);
5805         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5806         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5807
5808         let htlc_timeout = {
5809                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5810                 assert_eq!(node_txn.len(), 2);
5811                 check_spends!(node_txn[0], chan_1.3);
5812                 assert_eq!(node_txn[1].input.len(), 1);
5813                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5814                 check_spends!(node_txn[1], local_txn[0]);
5815                 node_txn[1].clone()
5816         };
5817
5818         mine_transaction(&nodes[0], &htlc_timeout);
5819         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5820         expect_payment_failed!(nodes[0], our_payment_hash, true);
5821
5822         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5823         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5824         assert_eq!(spend_txn.len(), 3);
5825         check_spends!(spend_txn[0], local_txn[0]);
5826         assert_eq!(spend_txn[1].input.len(), 1);
5827         check_spends!(spend_txn[1], htlc_timeout);
5828         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5829         assert_eq!(spend_txn[2].input.len(), 2);
5830         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5831         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5832                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5833 }
5834
5835 #[test]
5836 fn test_key_derivation_params() {
5837         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5838         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5839         // let us re-derive the channel key set to then derive a delayed_payment_key.
5840
5841         let chanmon_cfgs = create_chanmon_cfgs(3);
5842
5843         // We manually create the node configuration to backup the seed.
5844         let seed = [42; 32];
5845         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5846         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);
5847         let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5848         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() };
5849         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5850         node_cfgs.remove(0);
5851         node_cfgs.insert(0, node);
5852
5853         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5854         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5855
5856         // Create some initial channels
5857         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5858         // for node 0
5859         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5860         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5861         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5862
5863         // Ensure all nodes are at the same height
5864         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5865         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5866         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5867         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5868
5869         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5870         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5871         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5872         assert_eq!(local_txn_1[0].input.len(), 1);
5873         check_spends!(local_txn_1[0], chan_1.3);
5874
5875         // We check funding pubkey are unique
5876         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]));
5877         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]));
5878         if from_0_funding_key_0 == from_1_funding_key_0
5879             || from_0_funding_key_0 == from_1_funding_key_1
5880             || from_0_funding_key_1 == from_1_funding_key_0
5881             || from_0_funding_key_1 == from_1_funding_key_1 {
5882                 panic!("Funding pubkeys aren't unique");
5883         }
5884
5885         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5886         mine_transaction(&nodes[0], &local_txn_1[0]);
5887         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5888         check_closed_broadcast!(nodes[0], true);
5889         check_added_monitors!(nodes[0], 1);
5890         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5891
5892         let htlc_timeout = {
5893                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5894                 assert_eq!(node_txn[1].input.len(), 1);
5895                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5896                 check_spends!(node_txn[1], local_txn_1[0]);
5897                 node_txn[1].clone()
5898         };
5899
5900         mine_transaction(&nodes[0], &htlc_timeout);
5901         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5902         expect_payment_failed!(nodes[0], our_payment_hash, true);
5903
5904         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5905         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5906         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5907         assert_eq!(spend_txn.len(), 3);
5908         check_spends!(spend_txn[0], local_txn_1[0]);
5909         assert_eq!(spend_txn[1].input.len(), 1);
5910         check_spends!(spend_txn[1], htlc_timeout);
5911         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5912         assert_eq!(spend_txn[2].input.len(), 2);
5913         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5914         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5915                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5916 }
5917
5918 #[test]
5919 fn test_static_output_closing_tx() {
5920         let chanmon_cfgs = create_chanmon_cfgs(2);
5921         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5922         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5923         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5924
5925         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5926
5927         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5928         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5929
5930         mine_transaction(&nodes[0], &closing_tx);
5931         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5932         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5933
5934         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5935         assert_eq!(spend_txn.len(), 1);
5936         check_spends!(spend_txn[0], closing_tx);
5937
5938         mine_transaction(&nodes[1], &closing_tx);
5939         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5940         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5941
5942         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5943         assert_eq!(spend_txn.len(), 1);
5944         check_spends!(spend_txn[0], closing_tx);
5945 }
5946
5947 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5948         let chanmon_cfgs = create_chanmon_cfgs(2);
5949         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5950         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5951         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5952         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5953
5954         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5955
5956         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5957         // present in B's local commitment transaction, but none of A's commitment transactions.
5958         nodes[1].node.claim_funds(payment_preimage);
5959         check_added_monitors!(nodes[1], 1);
5960         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5961
5962         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5963         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5964         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5965
5966         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5967         check_added_monitors!(nodes[0], 1);
5968         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5969         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5970         check_added_monitors!(nodes[1], 1);
5971
5972         let starting_block = nodes[1].best_block_info();
5973         let mut block = Block {
5974                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5975                 txdata: vec![],
5976         };
5977         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5978                 connect_block(&nodes[1], &block);
5979                 block.header.prev_blockhash = block.block_hash();
5980         }
5981         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5982         check_closed_broadcast!(nodes[1], true);
5983         check_added_monitors!(nodes[1], 1);
5984         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5985 }
5986
5987 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5988         let chanmon_cfgs = create_chanmon_cfgs(2);
5989         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5990         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5991         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5992         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5993
5994         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5995         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5996         check_added_monitors!(nodes[0], 1);
5997
5998         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5999
6000         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
6001         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
6002         // to "time out" the HTLC.
6003
6004         let starting_block = nodes[1].best_block_info();
6005         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6006
6007         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
6008                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
6009                 header.prev_blockhash = header.block_hash();
6010         }
6011         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6012         check_closed_broadcast!(nodes[0], true);
6013         check_added_monitors!(nodes[0], 1);
6014         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6015 }
6016
6017 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
6018         let chanmon_cfgs = create_chanmon_cfgs(3);
6019         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6020         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6021         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6022         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6023
6024         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6025         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6026         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6027         // actually revoked.
6028         let htlc_value = if use_dust { 50000 } else { 3000000 };
6029         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6030         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6031         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6032         check_added_monitors!(nodes[1], 1);
6033
6034         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6035         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6036         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6037         check_added_monitors!(nodes[0], 1);
6038         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6039         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6040         check_added_monitors!(nodes[1], 1);
6041         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6042         check_added_monitors!(nodes[1], 1);
6043         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6044
6045         if check_revoke_no_close {
6046                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6047                 check_added_monitors!(nodes[0], 1);
6048         }
6049
6050         let starting_block = nodes[1].best_block_info();
6051         let mut block = Block {
6052                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6053                 txdata: vec![],
6054         };
6055         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6056                 connect_block(&nodes[0], &block);
6057                 block.header.prev_blockhash = block.block_hash();
6058         }
6059         if !check_revoke_no_close {
6060                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6061                 check_closed_broadcast!(nodes[0], true);
6062                 check_added_monitors!(nodes[0], 1);
6063                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6064         } else {
6065                 let events = nodes[0].node.get_and_clear_pending_events();
6066                 assert_eq!(events.len(), 2);
6067                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6068                         assert_eq!(*payment_hash, our_payment_hash);
6069                 } else { panic!("Unexpected event"); }
6070                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6071                         assert_eq!(*payment_hash, our_payment_hash);
6072                 } else { panic!("Unexpected event"); }
6073         }
6074 }
6075
6076 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6077 // There are only a few cases to test here:
6078 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
6079 //    broadcastable commitment transactions result in channel closure,
6080 //  * its included in an unrevoked-but-previous remote commitment transaction,
6081 //  * its included in the latest remote or local commitment transactions.
6082 // We test each of the three possible commitment transactions individually and use both dust and
6083 // non-dust HTLCs.
6084 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6085 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6086 // tested for at least one of the cases in other tests.
6087 #[test]
6088 fn htlc_claim_single_commitment_only_a() {
6089         do_htlc_claim_local_commitment_only(true);
6090         do_htlc_claim_local_commitment_only(false);
6091
6092         do_htlc_claim_current_remote_commitment_only(true);
6093         do_htlc_claim_current_remote_commitment_only(false);
6094 }
6095
6096 #[test]
6097 fn htlc_claim_single_commitment_only_b() {
6098         do_htlc_claim_previous_remote_commitment_only(true, false);
6099         do_htlc_claim_previous_remote_commitment_only(false, false);
6100         do_htlc_claim_previous_remote_commitment_only(true, true);
6101         do_htlc_claim_previous_remote_commitment_only(false, true);
6102 }
6103
6104 #[test]
6105 #[should_panic]
6106 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6107         let chanmon_cfgs = create_chanmon_cfgs(2);
6108         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6109         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6110         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6111         // Force duplicate randomness for every get-random call
6112         for node in nodes.iter() {
6113                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6114         }
6115
6116         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6117         let channel_value_satoshis=10000;
6118         let push_msat=10001;
6119         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6120         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6121         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6122         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6123
6124         // Create a second channel with the same random values. This used to panic due to a colliding
6125         // channel_id, but now panics due to a colliding outbound SCID alias.
6126         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6127 }
6128
6129 #[test]
6130 fn bolt2_open_channel_sending_node_checks_part2() {
6131         let chanmon_cfgs = create_chanmon_cfgs(2);
6132         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6133         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6134         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6135
6136         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6137         let channel_value_satoshis=2^24;
6138         let push_msat=10001;
6139         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6140
6141         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6142         let channel_value_satoshis=10000;
6143         // Test when push_msat is equal to 1000 * funding_satoshis.
6144         let push_msat=1000*channel_value_satoshis+1;
6145         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6146
6147         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6148         let channel_value_satoshis=10000;
6149         let push_msat=10001;
6150         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
6151         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6152         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6153
6154         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6155         // 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
6156         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6157
6158         // 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.
6159         assert!(BREAKDOWN_TIMEOUT>0);
6160         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6161
6162         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6163         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6164         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6165
6166         // 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.
6167         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6168         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6169         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6170         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6171         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6172 }
6173
6174 #[test]
6175 fn bolt2_open_channel_sane_dust_limit() {
6176         let chanmon_cfgs = create_chanmon_cfgs(2);
6177         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6178         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6179         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6180
6181         let channel_value_satoshis=1000000;
6182         let push_msat=10001;
6183         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6184         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6185         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6186         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6187
6188         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6189         let events = nodes[1].node.get_and_clear_pending_msg_events();
6190         let err_msg = match events[0] {
6191                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6192                         msg.clone()
6193                 },
6194                 _ => panic!("Unexpected event"),
6195         };
6196         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6197 }
6198
6199 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6200 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6201 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6202 // is no longer affordable once it's freed.
6203 #[test]
6204 fn test_fail_holding_cell_htlc_upon_free() {
6205         let chanmon_cfgs = create_chanmon_cfgs(2);
6206         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6207         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6208         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6209         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6210
6211         // First nodes[0] generates an update_fee, setting the channel's
6212         // pending_update_fee.
6213         {
6214                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6215                 *feerate_lock += 20;
6216         }
6217         nodes[0].node.timer_tick_occurred();
6218         check_added_monitors!(nodes[0], 1);
6219
6220         let events = nodes[0].node.get_and_clear_pending_msg_events();
6221         assert_eq!(events.len(), 1);
6222         let (update_msg, commitment_signed) = match events[0] {
6223                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6224                         (update_fee.as_ref(), commitment_signed)
6225                 },
6226                 _ => panic!("Unexpected event"),
6227         };
6228
6229         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6230
6231         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6232         let channel_reserve = chan_stat.channel_reserve_msat;
6233         let feerate = get_feerate!(nodes[0], chan.2);
6234         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6235
6236         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6237         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6238         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6239
6240         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6241         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6242         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6243         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6244
6245         // Flush the pending fee update.
6246         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6247         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6248         check_added_monitors!(nodes[1], 1);
6249         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6250         check_added_monitors!(nodes[0], 1);
6251
6252         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6253         // HTLC, but now that the fee has been raised the payment will now fail, causing
6254         // us to surface its failure to the user.
6255         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6256         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6257         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);
6258         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 {}",
6259                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6260         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6261
6262         // Check that the payment failed to be sent out.
6263         let events = nodes[0].node.get_and_clear_pending_events();
6264         assert_eq!(events.len(), 1);
6265         match &events[0] {
6266                 &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, .. } => {
6267                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6268                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6269                         assert_eq!(*rejected_by_dest, false);
6270                         assert_eq!(*all_paths_failed, true);
6271                         assert_eq!(*network_update, None);
6272                         assert_eq!(*short_channel_id, None);
6273                         assert_eq!(*error_code, None);
6274                         assert_eq!(*error_data, None);
6275                 },
6276                 _ => panic!("Unexpected event"),
6277         }
6278 }
6279
6280 // Test that if multiple HTLCs are released from the holding cell and one is
6281 // valid but the other is no longer valid upon release, the valid HTLC can be
6282 // successfully completed while the other one fails as expected.
6283 #[test]
6284 fn test_free_and_fail_holding_cell_htlcs() {
6285         let chanmon_cfgs = create_chanmon_cfgs(2);
6286         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6287         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6288         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6289         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6290
6291         // First nodes[0] generates an update_fee, setting the channel's
6292         // pending_update_fee.
6293         {
6294                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6295                 *feerate_lock += 200;
6296         }
6297         nodes[0].node.timer_tick_occurred();
6298         check_added_monitors!(nodes[0], 1);
6299
6300         let events = nodes[0].node.get_and_clear_pending_msg_events();
6301         assert_eq!(events.len(), 1);
6302         let (update_msg, commitment_signed) = match events[0] {
6303                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6304                         (update_fee.as_ref(), commitment_signed)
6305                 },
6306                 _ => panic!("Unexpected event"),
6307         };
6308
6309         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6310
6311         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6312         let channel_reserve = chan_stat.channel_reserve_msat;
6313         let feerate = get_feerate!(nodes[0], chan.2);
6314         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6315
6316         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6317         let amt_1 = 20000;
6318         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6319         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6320         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6321
6322         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6323         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6324         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6325         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6326         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6327         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6328         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6329
6330         // Flush the pending fee update.
6331         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6332         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6333         check_added_monitors!(nodes[1], 1);
6334         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6335         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6336         check_added_monitors!(nodes[0], 2);
6337
6338         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6339         // but now that the fee has been raised the second payment will now fail, causing us
6340         // to surface its failure to the user. The first payment should succeed.
6341         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6342         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6343         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);
6344         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 {}",
6345                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6346         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6347
6348         // Check that the second payment failed to be sent out.
6349         let events = nodes[0].node.get_and_clear_pending_events();
6350         assert_eq!(events.len(), 1);
6351         match &events[0] {
6352                 &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, .. } => {
6353                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6354                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6355                         assert_eq!(*rejected_by_dest, false);
6356                         assert_eq!(*all_paths_failed, true);
6357                         assert_eq!(*network_update, None);
6358                         assert_eq!(*short_channel_id, None);
6359                         assert_eq!(*error_code, None);
6360                         assert_eq!(*error_data, None);
6361                 },
6362                 _ => panic!("Unexpected event"),
6363         }
6364
6365         // Complete the first payment and the RAA from the fee update.
6366         let (payment_event, send_raa_event) = {
6367                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6368                 assert_eq!(msgs.len(), 2);
6369                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6370         };
6371         let raa = match send_raa_event {
6372                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6373                 _ => panic!("Unexpected event"),
6374         };
6375         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6376         check_added_monitors!(nodes[1], 1);
6377         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6378         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6379         let events = nodes[1].node.get_and_clear_pending_events();
6380         assert_eq!(events.len(), 1);
6381         match events[0] {
6382                 Event::PendingHTLCsForwardable { .. } => {},
6383                 _ => panic!("Unexpected event"),
6384         }
6385         nodes[1].node.process_pending_htlc_forwards();
6386         let events = nodes[1].node.get_and_clear_pending_events();
6387         assert_eq!(events.len(), 1);
6388         match events[0] {
6389                 Event::PaymentReceived { .. } => {},
6390                 _ => panic!("Unexpected event"),
6391         }
6392         nodes[1].node.claim_funds(payment_preimage_1);
6393         check_added_monitors!(nodes[1], 1);
6394         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6395
6396         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6397         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6398         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6399         expect_payment_sent!(nodes[0], payment_preimage_1);
6400 }
6401
6402 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6403 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6404 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6405 // once it's freed.
6406 #[test]
6407 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6408         let chanmon_cfgs = create_chanmon_cfgs(3);
6409         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6410         // When this test was written, the default base fee floated based on the HTLC count.
6411         // It is now fixed, so we simply set the fee to the expected value here.
6412         let mut config = test_default_channel_config();
6413         config.channel_config.forwarding_fee_base_msat = 196;
6414         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6415         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6416         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6417         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6418
6419         // First nodes[1] generates an update_fee, setting the channel's
6420         // pending_update_fee.
6421         {
6422                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6423                 *feerate_lock += 20;
6424         }
6425         nodes[1].node.timer_tick_occurred();
6426         check_added_monitors!(nodes[1], 1);
6427
6428         let events = nodes[1].node.get_and_clear_pending_msg_events();
6429         assert_eq!(events.len(), 1);
6430         let (update_msg, commitment_signed) = match events[0] {
6431                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6432                         (update_fee.as_ref(), commitment_signed)
6433                 },
6434                 _ => panic!("Unexpected event"),
6435         };
6436
6437         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6438
6439         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6440         let channel_reserve = chan_stat.channel_reserve_msat;
6441         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6442         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6443
6444         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6445         let feemsat = 239;
6446         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6447         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6448         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6449         let payment_event = {
6450                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6451                 check_added_monitors!(nodes[0], 1);
6452
6453                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6454                 assert_eq!(events.len(), 1);
6455
6456                 SendEvent::from_event(events.remove(0))
6457         };
6458         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6459         check_added_monitors!(nodes[1], 0);
6460         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6461         expect_pending_htlcs_forwardable!(nodes[1]);
6462
6463         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6464         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6465
6466         // Flush the pending fee update.
6467         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6468         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6469         check_added_monitors!(nodes[2], 1);
6470         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6471         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6472         check_added_monitors!(nodes[1], 2);
6473
6474         // A final RAA message is generated to finalize the fee update.
6475         let events = nodes[1].node.get_and_clear_pending_msg_events();
6476         assert_eq!(events.len(), 1);
6477
6478         let raa_msg = match &events[0] {
6479                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6480                         msg.clone()
6481                 },
6482                 _ => panic!("Unexpected event"),
6483         };
6484
6485         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6486         check_added_monitors!(nodes[2], 1);
6487         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6488
6489         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6490         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6491         assert_eq!(process_htlc_forwards_event.len(), 2);
6492         match &process_htlc_forwards_event[0] {
6493                 &Event::PendingHTLCsForwardable { .. } => {},
6494                 _ => panic!("Unexpected event"),
6495         }
6496
6497         // In response, we call ChannelManager's process_pending_htlc_forwards
6498         nodes[1].node.process_pending_htlc_forwards();
6499         check_added_monitors!(nodes[1], 1);
6500
6501         // This causes the HTLC to be failed backwards.
6502         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6503         assert_eq!(fail_event.len(), 1);
6504         let (fail_msg, commitment_signed) = match &fail_event[0] {
6505                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6506                         assert_eq!(updates.update_add_htlcs.len(), 0);
6507                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6508                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6509                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6510                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6511                 },
6512                 _ => panic!("Unexpected event"),
6513         };
6514
6515         // Pass the failure messages back to nodes[0].
6516         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6517         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6518
6519         // Complete the HTLC failure+removal process.
6520         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6521         check_added_monitors!(nodes[0], 1);
6522         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6523         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6524         check_added_monitors!(nodes[1], 2);
6525         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6526         assert_eq!(final_raa_event.len(), 1);
6527         let raa = match &final_raa_event[0] {
6528                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6529                 _ => panic!("Unexpected event"),
6530         };
6531         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6532         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6533         check_added_monitors!(nodes[0], 1);
6534 }
6535
6536 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6537 // 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.
6538 //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.
6539
6540 #[test]
6541 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6542         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6543         let chanmon_cfgs = create_chanmon_cfgs(2);
6544         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6545         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6546         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6547         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6548
6549         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6550         route.paths[0][0].fee_msat = 100;
6551
6552         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6553                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6554         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6555         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6556 }
6557
6558 #[test]
6559 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6560         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6561         let chanmon_cfgs = create_chanmon_cfgs(2);
6562         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6563         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6564         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6565         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6566
6567         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6568         route.paths[0][0].fee_msat = 0;
6569         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6570                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6571
6572         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6573         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6574 }
6575
6576 #[test]
6577 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6578         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6579         let chanmon_cfgs = create_chanmon_cfgs(2);
6580         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6581         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6582         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6583         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6584
6585         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6586         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6587         check_added_monitors!(nodes[0], 1);
6588         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6589         updates.update_add_htlcs[0].amount_msat = 0;
6590
6591         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6592         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6593         check_closed_broadcast!(nodes[1], true).unwrap();
6594         check_added_monitors!(nodes[1], 1);
6595         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6596 }
6597
6598 #[test]
6599 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6600         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6601         //It is enforced when constructing a route.
6602         let chanmon_cfgs = create_chanmon_cfgs(2);
6603         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6604         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6605         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6606         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6607
6608         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6609                 .with_features(InvoiceFeatures::known());
6610         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6611         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6612         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6613                 assert_eq!(err, &"Channel CLTV overflowed?"));
6614 }
6615
6616 #[test]
6617 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6618         //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.
6619         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6620         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6621         let chanmon_cfgs = create_chanmon_cfgs(2);
6622         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6623         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6624         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6625         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6626         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6627
6628         for i in 0..max_accepted_htlcs {
6629                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6630                 let payment_event = {
6631                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6632                         check_added_monitors!(nodes[0], 1);
6633
6634                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6635                         assert_eq!(events.len(), 1);
6636                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6637                                 assert_eq!(htlcs[0].htlc_id, i);
6638                         } else {
6639                                 assert!(false);
6640                         }
6641                         SendEvent::from_event(events.remove(0))
6642                 };
6643                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6644                 check_added_monitors!(nodes[1], 0);
6645                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6646
6647                 expect_pending_htlcs_forwardable!(nodes[1]);
6648                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6649         }
6650         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6651         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6652                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6653
6654         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6655         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6656 }
6657
6658 #[test]
6659 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6660         //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.
6661         let chanmon_cfgs = create_chanmon_cfgs(2);
6662         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6663         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6664         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6665         let channel_value = 100000;
6666         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6667         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6668
6669         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6670
6671         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6672         // Manually create a route over our max in flight (which our router normally automatically
6673         // limits us to.
6674         route.paths[0][0].fee_msat =  max_in_flight + 1;
6675         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6676                 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)));
6677
6678         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6679         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);
6680
6681         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6682 }
6683
6684 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6685 #[test]
6686 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6687         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6688         let chanmon_cfgs = create_chanmon_cfgs(2);
6689         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6690         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6691         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6692         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6693         let htlc_minimum_msat: u64;
6694         {
6695                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6696                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6697                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6698         }
6699
6700         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6701         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6702         check_added_monitors!(nodes[0], 1);
6703         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6704         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6705         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6706         assert!(nodes[1].node.list_channels().is_empty());
6707         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6708         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()));
6709         check_added_monitors!(nodes[1], 1);
6710         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6711 }
6712
6713 #[test]
6714 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6715         //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
6716         let chanmon_cfgs = create_chanmon_cfgs(2);
6717         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6718         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6719         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6720         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6721
6722         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6723         let channel_reserve = chan_stat.channel_reserve_msat;
6724         let feerate = get_feerate!(nodes[0], chan.2);
6725         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6726         // The 2* and +1 are for the fee spike reserve.
6727         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6728
6729         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6730         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6731         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6732         check_added_monitors!(nodes[0], 1);
6733         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6734
6735         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6736         // at this time channel-initiatee receivers are not required to enforce that senders
6737         // respect the fee_spike_reserve.
6738         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6739         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6740
6741         assert!(nodes[1].node.list_channels().is_empty());
6742         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6743         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6744         check_added_monitors!(nodes[1], 1);
6745         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6746 }
6747
6748 #[test]
6749 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6750         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6751         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6752         let chanmon_cfgs = create_chanmon_cfgs(2);
6753         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6754         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6755         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6756         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6757
6758         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6759         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6760         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6761         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6762         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6763         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6764
6765         let mut msg = msgs::UpdateAddHTLC {
6766                 channel_id: chan.2,
6767                 htlc_id: 0,
6768                 amount_msat: 1000,
6769                 payment_hash: our_payment_hash,
6770                 cltv_expiry: htlc_cltv,
6771                 onion_routing_packet: onion_packet.clone(),
6772         };
6773
6774         for i in 0..super::channel::OUR_MAX_HTLCS {
6775                 msg.htlc_id = i as u64;
6776                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6777         }
6778         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6779         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6780
6781         assert!(nodes[1].node.list_channels().is_empty());
6782         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6783         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6784         check_added_monitors!(nodes[1], 1);
6785         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6786 }
6787
6788 #[test]
6789 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6790         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6791         let chanmon_cfgs = create_chanmon_cfgs(2);
6792         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6793         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6794         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6795         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6796
6797         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6798         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6799         check_added_monitors!(nodes[0], 1);
6800         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6801         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6802         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6803
6804         assert!(nodes[1].node.list_channels().is_empty());
6805         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6806         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6807         check_added_monitors!(nodes[1], 1);
6808         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6809 }
6810
6811 #[test]
6812 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6813         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
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_with_value(&nodes, 0, 1, 100000, 95000000, 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 mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6824         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6825         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6826
6827         assert!(nodes[1].node.list_channels().is_empty());
6828         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6829         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6830         check_added_monitors!(nodes[1], 1);
6831         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6832 }
6833
6834 #[test]
6835 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6836         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6837         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6838         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6839         let chanmon_cfgs = create_chanmon_cfgs(2);
6840         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6841         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6842         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6843
6844         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6845         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6846         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6847         check_added_monitors!(nodes[0], 1);
6848         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6849         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6850
6851         //Disconnect and Reconnect
6852         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6853         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6854         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6855         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6856         assert_eq!(reestablish_1.len(), 1);
6857         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6858         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6859         assert_eq!(reestablish_2.len(), 1);
6860         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6861         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6862         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6863         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6864
6865         //Resend HTLC
6866         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6867         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6868         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6869         check_added_monitors!(nodes[1], 1);
6870         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6871
6872         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6873
6874         assert!(nodes[1].node.list_channels().is_empty());
6875         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6876         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6877         check_added_monitors!(nodes[1], 1);
6878         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6879 }
6880
6881 #[test]
6882 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6883         //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.
6884
6885         let chanmon_cfgs = create_chanmon_cfgs(2);
6886         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6887         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6888         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6889         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6890         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6891         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6892
6893         check_added_monitors!(nodes[0], 1);
6894         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6895         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6896
6897         let update_msg = msgs::UpdateFulfillHTLC{
6898                 channel_id: chan.2,
6899                 htlc_id: 0,
6900                 payment_preimage: our_payment_preimage,
6901         };
6902
6903         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6904
6905         assert!(nodes[0].node.list_channels().is_empty());
6906         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6907         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()));
6908         check_added_monitors!(nodes[0], 1);
6909         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6910 }
6911
6912 #[test]
6913 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6914         //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.
6915
6916         let chanmon_cfgs = create_chanmon_cfgs(2);
6917         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6918         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6919         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6920         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6921
6922         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6923         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6924         check_added_monitors!(nodes[0], 1);
6925         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6926         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6927
6928         let update_msg = msgs::UpdateFailHTLC{
6929                 channel_id: chan.2,
6930                 htlc_id: 0,
6931                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6932         };
6933
6934         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6935
6936         assert!(nodes[0].node.list_channels().is_empty());
6937         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6938         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()));
6939         check_added_monitors!(nodes[0], 1);
6940         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6941 }
6942
6943 #[test]
6944 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6945         //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.
6946
6947         let chanmon_cfgs = create_chanmon_cfgs(2);
6948         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6949         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6950         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6951         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6952
6953         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6954         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6955         check_added_monitors!(nodes[0], 1);
6956         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6957         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6958         let update_msg = msgs::UpdateFailMalformedHTLC{
6959                 channel_id: chan.2,
6960                 htlc_id: 0,
6961                 sha256_of_onion: [1; 32],
6962                 failure_code: 0x8000,
6963         };
6964
6965         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6966
6967         assert!(nodes[0].node.list_channels().is_empty());
6968         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6969         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()));
6970         check_added_monitors!(nodes[0], 1);
6971         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6972 }
6973
6974 #[test]
6975 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6976         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6977
6978         let chanmon_cfgs = create_chanmon_cfgs(2);
6979         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6980         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6981         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6982         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6983
6984         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6985
6986         nodes[1].node.claim_funds(our_payment_preimage);
6987         check_added_monitors!(nodes[1], 1);
6988         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6989
6990         let events = nodes[1].node.get_and_clear_pending_msg_events();
6991         assert_eq!(events.len(), 1);
6992         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6993                 match events[0] {
6994                         MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6995                                 assert!(update_add_htlcs.is_empty());
6996                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6997                                 assert!(update_fail_htlcs.is_empty());
6998                                 assert!(update_fail_malformed_htlcs.is_empty());
6999                                 assert!(update_fee.is_none());
7000                                 update_fulfill_htlcs[0].clone()
7001                         },
7002                         _ => panic!("Unexpected event"),
7003                 }
7004         };
7005
7006         update_fulfill_msg.htlc_id = 1;
7007
7008         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7009
7010         assert!(nodes[0].node.list_channels().is_empty());
7011         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7012         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
7013         check_added_monitors!(nodes[0], 1);
7014         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7015 }
7016
7017 #[test]
7018 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
7019         //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.
7020
7021         let chanmon_cfgs = create_chanmon_cfgs(2);
7022         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7023         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7024         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7025         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7026
7027         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
7028
7029         nodes[1].node.claim_funds(our_payment_preimage);
7030         check_added_monitors!(nodes[1], 1);
7031         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7032
7033         let events = nodes[1].node.get_and_clear_pending_msg_events();
7034         assert_eq!(events.len(), 1);
7035         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7036                 match events[0] {
7037                         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, .. } } => {
7038                                 assert!(update_add_htlcs.is_empty());
7039                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7040                                 assert!(update_fail_htlcs.is_empty());
7041                                 assert!(update_fail_malformed_htlcs.is_empty());
7042                                 assert!(update_fee.is_none());
7043                                 update_fulfill_htlcs[0].clone()
7044                         },
7045                         _ => panic!("Unexpected event"),
7046                 }
7047         };
7048
7049         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7050
7051         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7052
7053         assert!(nodes[0].node.list_channels().is_empty());
7054         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7055         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7056         check_added_monitors!(nodes[0], 1);
7057         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7058 }
7059
7060 #[test]
7061 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7062         //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.
7063
7064         let chanmon_cfgs = create_chanmon_cfgs(2);
7065         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7066         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7067         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7068         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7069
7070         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7071         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7072         check_added_monitors!(nodes[0], 1);
7073
7074         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7075         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7076
7077         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7078         check_added_monitors!(nodes[1], 0);
7079         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7080
7081         let events = nodes[1].node.get_and_clear_pending_msg_events();
7082
7083         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7084                 match events[0] {
7085                         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, .. } } => {
7086                                 assert!(update_add_htlcs.is_empty());
7087                                 assert!(update_fulfill_htlcs.is_empty());
7088                                 assert!(update_fail_htlcs.is_empty());
7089                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7090                                 assert!(update_fee.is_none());
7091                                 update_fail_malformed_htlcs[0].clone()
7092                         },
7093                         _ => panic!("Unexpected event"),
7094                 }
7095         };
7096         update_msg.failure_code &= !0x8000;
7097         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7098
7099         assert!(nodes[0].node.list_channels().is_empty());
7100         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7101         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7102         check_added_monitors!(nodes[0], 1);
7103         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7104 }
7105
7106 #[test]
7107 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7108         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7109         //    * 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.
7110
7111         let chanmon_cfgs = create_chanmon_cfgs(3);
7112         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7113         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7114         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7115         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7116         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7117
7118         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7119
7120         //First hop
7121         let mut payment_event = {
7122                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7123                 check_added_monitors!(nodes[0], 1);
7124                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7125                 assert_eq!(events.len(), 1);
7126                 SendEvent::from_event(events.remove(0))
7127         };
7128         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7129         check_added_monitors!(nodes[1], 0);
7130         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7131         expect_pending_htlcs_forwardable!(nodes[1]);
7132         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7133         assert_eq!(events_2.len(), 1);
7134         check_added_monitors!(nodes[1], 1);
7135         payment_event = SendEvent::from_event(events_2.remove(0));
7136         assert_eq!(payment_event.msgs.len(), 1);
7137
7138         //Second Hop
7139         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7140         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7141         check_added_monitors!(nodes[2], 0);
7142         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7143
7144         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7145         assert_eq!(events_3.len(), 1);
7146         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7147                 match events_3[0] {
7148                         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 } } => {
7149                                 assert!(update_add_htlcs.is_empty());
7150                                 assert!(update_fulfill_htlcs.is_empty());
7151                                 assert!(update_fail_htlcs.is_empty());
7152                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7153                                 assert!(update_fee.is_none());
7154                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7155                         },
7156                         _ => panic!("Unexpected event"),
7157                 }
7158         };
7159
7160         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7161
7162         check_added_monitors!(nodes[1], 0);
7163         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7164         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
7165         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7166         assert_eq!(events_4.len(), 1);
7167
7168         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7169         match events_4[0] {
7170                 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, .. } } => {
7171                         assert!(update_add_htlcs.is_empty());
7172                         assert!(update_fulfill_htlcs.is_empty());
7173                         assert_eq!(update_fail_htlcs.len(), 1);
7174                         assert!(update_fail_malformed_htlcs.is_empty());
7175                         assert!(update_fee.is_none());
7176                 },
7177                 _ => panic!("Unexpected event"),
7178         };
7179
7180         check_added_monitors!(nodes[1], 1);
7181 }
7182
7183 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7184         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7185         // 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
7186         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7187
7188         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7189         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7190         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7191         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7192         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7193         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7194
7195         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7196
7197         // We route 2 dust-HTLCs between A and B
7198         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7199         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7200         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7201
7202         // Cache one local commitment tx as previous
7203         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7204
7205         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7206         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7207         check_added_monitors!(nodes[1], 0);
7208         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7209         check_added_monitors!(nodes[1], 1);
7210
7211         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7212         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7213         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7214         check_added_monitors!(nodes[0], 1);
7215
7216         // Cache one local commitment tx as lastest
7217         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7218
7219         let events = nodes[0].node.get_and_clear_pending_msg_events();
7220         match events[0] {
7221                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7222                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7223                 },
7224                 _ => panic!("Unexpected event"),
7225         }
7226         match events[1] {
7227                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7228                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7229                 },
7230                 _ => panic!("Unexpected event"),
7231         }
7232
7233         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7234         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7235         if announce_latest {
7236                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7237         } else {
7238                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7239         }
7240
7241         check_closed_broadcast!(nodes[0], true);
7242         check_added_monitors!(nodes[0], 1);
7243         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7244
7245         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7246         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7247         let events = nodes[0].node.get_and_clear_pending_events();
7248         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7249         assert_eq!(events.len(), 2);
7250         let mut first_failed = false;
7251         for event in events {
7252                 match event {
7253                         Event::PaymentPathFailed { payment_hash, .. } => {
7254                                 if payment_hash == payment_hash_1 {
7255                                         assert!(!first_failed);
7256                                         first_failed = true;
7257                                 } else {
7258                                         assert_eq!(payment_hash, payment_hash_2);
7259                                 }
7260                         }
7261                         _ => panic!("Unexpected event"),
7262                 }
7263         }
7264 }
7265
7266 #[test]
7267 fn test_failure_delay_dust_htlc_local_commitment() {
7268         do_test_failure_delay_dust_htlc_local_commitment(true);
7269         do_test_failure_delay_dust_htlc_local_commitment(false);
7270 }
7271
7272 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7273         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7274         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7275         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7276         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7277         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7278         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7279
7280         let chanmon_cfgs = create_chanmon_cfgs(3);
7281         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7282         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7283         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7284         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7285
7286         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7287
7288         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7289         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7290
7291         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7292         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7293
7294         // We revoked bs_commitment_tx
7295         if revoked {
7296                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7297                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7298         }
7299
7300         let mut timeout_tx = Vec::new();
7301         if local {
7302                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7303                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7304                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7305                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7306                 expect_payment_failed!(nodes[0], dust_hash, true);
7307
7308                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7309                 check_closed_broadcast!(nodes[0], true);
7310                 check_added_monitors!(nodes[0], 1);
7311                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7312                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7313                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7314                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7315                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7316                 mine_transaction(&nodes[0], &timeout_tx[0]);
7317                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7318                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7319         } else {
7320                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7321                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7322                 check_closed_broadcast!(nodes[0], true);
7323                 check_added_monitors!(nodes[0], 1);
7324                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7325                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7326
7327                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7328                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7329                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7330                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7331                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7332                 // dust HTLC should have been failed.
7333                 expect_payment_failed!(nodes[0], dust_hash, true);
7334
7335                 if !revoked {
7336                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7337                 } else {
7338                         assert_eq!(timeout_tx[0].lock_time, 0);
7339                 }
7340                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7341                 mine_transaction(&nodes[0], &timeout_tx[0]);
7342                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7343                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7344                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7345         }
7346 }
7347
7348 #[test]
7349 fn test_sweep_outbound_htlc_failure_update() {
7350         do_test_sweep_outbound_htlc_failure_update(false, true);
7351         do_test_sweep_outbound_htlc_failure_update(false, false);
7352         do_test_sweep_outbound_htlc_failure_update(true, false);
7353 }
7354
7355 #[test]
7356 fn test_user_configurable_csv_delay() {
7357         // We test our channel constructors yield errors when we pass them absurd csv delay
7358
7359         let mut low_our_to_self_config = UserConfig::default();
7360         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7361         let mut high_their_to_self_config = UserConfig::default();
7362         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7363         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7364         let chanmon_cfgs = create_chanmon_cfgs(2);
7365         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7366         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7367         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7368
7369         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7370         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7371                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7372                 &low_our_to_self_config, 0, 42)
7373         {
7374                 match error {
7375                         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())); },
7376                         _ => panic!("Unexpected event"),
7377                 }
7378         } else { assert!(false) }
7379
7380         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7381         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7382         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7383         open_channel.to_self_delay = 200;
7384         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7385                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7386                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7387         {
7388                 match error {
7389                         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()));  },
7390                         _ => panic!("Unexpected event"),
7391                 }
7392         } else { assert!(false); }
7393
7394         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7395         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7396         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()));
7397         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7398         accept_channel.to_self_delay = 200;
7399         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7400         let reason_msg;
7401         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7402                 match action {
7403                         &ErrorAction::SendErrorMessage { ref msg } => {
7404                                 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()));
7405                                 reason_msg = msg.data.clone();
7406                         },
7407                         _ => { panic!(); }
7408                 }
7409         } else { panic!(); }
7410         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7411
7412         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7413         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7414         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7415         open_channel.to_self_delay = 200;
7416         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7417                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7418                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7419         {
7420                 match error {
7421                         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())); },
7422                         _ => panic!("Unexpected event"),
7423                 }
7424         } else { assert!(false); }
7425 }
7426
7427 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7428         // When we get a data_loss_protect proving we're behind, we immediately panic as the
7429         // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7430         // panic message informs the user they should force-close without broadcasting, which is tested
7431         // if `reconnect_panicing` is not set.
7432         let persister;
7433         let logger;
7434         let fee_estimator;
7435         let tx_broadcaster;
7436         let chain_source;
7437         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7438         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7439         // during signing due to revoked tx
7440         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7441         let keys_manager = &chanmon_cfgs[0].keys_manager;
7442         let monitor;
7443         let node_state_0;
7444         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7445         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7446         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7447
7448         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7449
7450         // Cache node A state before any channel update
7451         let previous_node_state = nodes[0].node.encode();
7452         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7453         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7454
7455         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7456         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7457
7458         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7459         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7460
7461         // Restore node A from previous state
7462         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7463         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7464         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7465         tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7466         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7467         persister = test_utils::TestPersister::new();
7468         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7469         node_state_0 = {
7470                 let mut channel_monitors = HashMap::new();
7471                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7472                 <(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 {
7473                         keys_manager: keys_manager,
7474                         fee_estimator: &fee_estimator,
7475                         chain_monitor: &monitor,
7476                         logger: &logger,
7477                         tx_broadcaster: &tx_broadcaster,
7478                         default_config: UserConfig::default(),
7479                         channel_monitors,
7480                 }).unwrap().1
7481         };
7482         nodes[0].node = &node_state_0;
7483         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7484         nodes[0].chain_monitor = &monitor;
7485         nodes[0].chain_source = &chain_source;
7486
7487         check_added_monitors!(nodes[0], 1);
7488
7489         if reconnect_panicing {
7490                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7491                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7492
7493                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7494
7495                 // Check we close channel detecting A is fallen-behind
7496                 // Check that we sent the warning message when we detected that A has fallen behind,
7497                 // and give the possibility for A to recover from the warning.
7498                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7499                 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7500                 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7501
7502                 {
7503                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7504                         // The node B should not broadcast the transaction to force close the channel!
7505                         assert!(node_txn.is_empty());
7506                 }
7507
7508                 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7509                 // Check A panics upon seeing proof it has fallen behind.
7510                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7511                 return; // By this point we should have panic'ed!
7512         }
7513
7514         nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7515         check_added_monitors!(nodes[0], 1);
7516         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7517         {
7518                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7519                 assert_eq!(node_txn.len(), 0);
7520         }
7521
7522         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7523                 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7524                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7525                         match action {
7526                                 &ErrorAction::SendErrorMessage { ref msg } => {
7527                                         assert_eq!(msg.data, "Channel force-closed");
7528                                 },
7529                                 _ => panic!("Unexpected event!"),
7530                         }
7531                 } else {
7532                         panic!("Unexpected event {:?}", msg)
7533                 }
7534         }
7535
7536         // after the warning message sent by B, we should not able to
7537         // use the channel, or reconnect with success to the channel.
7538         assert!(nodes[0].node.list_usable_channels().is_empty());
7539         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7540         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7541         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7542
7543         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7544         let mut err_msgs_0 = Vec::with_capacity(1);
7545         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7546                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7547                         match action {
7548                                 &ErrorAction::SendErrorMessage { ref msg } => {
7549                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7550                                         err_msgs_0.push(msg.clone());
7551                                 },
7552                                 _ => panic!("Unexpected event!"),
7553                         }
7554                 } else {
7555                         panic!("Unexpected event!");
7556                 }
7557         }
7558         assert_eq!(err_msgs_0.len(), 1);
7559         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7560         assert!(nodes[1].node.list_usable_channels().is_empty());
7561         check_added_monitors!(nodes[1], 1);
7562         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7563         check_closed_broadcast!(nodes[1], false);
7564 }
7565
7566 #[test]
7567 #[should_panic]
7568 fn test_data_loss_protect_showing_stale_state_panics() {
7569         do_test_data_loss_protect(true);
7570 }
7571
7572 #[test]
7573 fn test_force_close_without_broadcast() {
7574         do_test_data_loss_protect(false);
7575 }
7576
7577 #[test]
7578 fn test_check_htlc_underpaying() {
7579         // Send payment through A -> B but A is maliciously
7580         // sending a probe payment (i.e less than expected value0
7581         // to B, B should refuse payment.
7582
7583         let chanmon_cfgs = create_chanmon_cfgs(2);
7584         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7585         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7586         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7587
7588         // Create some initial channels
7589         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7590
7591         let scorer = test_utils::TestScorer::with_penalty(0);
7592         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7593         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7594         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();
7595         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7596         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7597         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7598         check_added_monitors!(nodes[0], 1);
7599
7600         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7601         assert_eq!(events.len(), 1);
7602         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7603         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7604         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7605
7606         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7607         // and then will wait a second random delay before failing the HTLC back:
7608         expect_pending_htlcs_forwardable!(nodes[1]);
7609         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7610
7611         // Node 3 is expecting payment of 100_000 but received 10_000,
7612         // it should fail htlc like we didn't know the preimage.
7613         nodes[1].node.process_pending_htlc_forwards();
7614
7615         let events = nodes[1].node.get_and_clear_pending_msg_events();
7616         assert_eq!(events.len(), 1);
7617         let (update_fail_htlc, commitment_signed) = match events[0] {
7618                 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 } } => {
7619                         assert!(update_add_htlcs.is_empty());
7620                         assert!(update_fulfill_htlcs.is_empty());
7621                         assert_eq!(update_fail_htlcs.len(), 1);
7622                         assert!(update_fail_malformed_htlcs.is_empty());
7623                         assert!(update_fee.is_none());
7624                         (update_fail_htlcs[0].clone(), commitment_signed)
7625                 },
7626                 _ => panic!("Unexpected event"),
7627         };
7628         check_added_monitors!(nodes[1], 1);
7629
7630         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7631         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7632
7633         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7634         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7635         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7636         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7637 }
7638
7639 #[test]
7640 fn test_announce_disable_channels() {
7641         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7642         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7643
7644         let chanmon_cfgs = create_chanmon_cfgs(2);
7645         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7646         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7647         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7648
7649         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7650         create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7651         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7652
7653         // Disconnect peers
7654         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7655         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7656
7657         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7658         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7659         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7660         assert_eq!(msg_events.len(), 3);
7661         let mut chans_disabled = HashMap::new();
7662         for e in msg_events {
7663                 match e {
7664                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7665                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7666                                 // Check that each channel gets updated exactly once
7667                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7668                                         panic!("Generated ChannelUpdate for wrong chan!");
7669                                 }
7670                         },
7671                         _ => panic!("Unexpected event"),
7672                 }
7673         }
7674         // Reconnect peers
7675         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7676         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7677         assert_eq!(reestablish_1.len(), 3);
7678         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7679         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7680         assert_eq!(reestablish_2.len(), 3);
7681
7682         // Reestablish chan_1
7683         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7684         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7685         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7686         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7687         // Reestablish chan_2
7688         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7689         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7690         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7691         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7692         // Reestablish chan_3
7693         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7694         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7695         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7696         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7697
7698         nodes[0].node.timer_tick_occurred();
7699         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7700         nodes[0].node.timer_tick_occurred();
7701         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7702         assert_eq!(msg_events.len(), 3);
7703         for e in msg_events {
7704                 match e {
7705                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7706                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7707                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7708                                         // Each update should have a higher timestamp than the previous one, replacing
7709                                         // the old one.
7710                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7711                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7712                                 }
7713                         },
7714                         _ => panic!("Unexpected event"),
7715                 }
7716         }
7717         // Check that each channel gets updated exactly once
7718         assert!(chans_disabled.is_empty());
7719 }
7720
7721 #[test]
7722 fn test_bump_penalty_txn_on_revoked_commitment() {
7723         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7724         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7725
7726         let chanmon_cfgs = create_chanmon_cfgs(2);
7727         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7728         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7729         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7730
7731         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7732
7733         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7734         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7735                 .with_features(InvoiceFeatures::known());
7736         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7737         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7738
7739         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7740         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7741         assert_eq!(revoked_txn[0].output.len(), 4);
7742         assert_eq!(revoked_txn[0].input.len(), 1);
7743         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7744         let revoked_txid = revoked_txn[0].txid();
7745
7746         let mut penalty_sum = 0;
7747         for outp in revoked_txn[0].output.iter() {
7748                 if outp.script_pubkey.is_v0_p2wsh() {
7749                         penalty_sum += outp.value;
7750                 }
7751         }
7752
7753         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7754         let header_114 = connect_blocks(&nodes[1], 14);
7755
7756         // Actually revoke tx by claiming a HTLC
7757         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7758         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7759         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7760         check_added_monitors!(nodes[1], 1);
7761
7762         // One or more justice tx should have been broadcast, check it
7763         let penalty_1;
7764         let feerate_1;
7765         {
7766                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7767                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7768                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7769                 assert_eq!(node_txn[0].output.len(), 1);
7770                 check_spends!(node_txn[0], revoked_txn[0]);
7771                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7772                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7773                 penalty_1 = node_txn[0].txid();
7774                 node_txn.clear();
7775         };
7776
7777         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7778         connect_blocks(&nodes[1], 15);
7779         let mut penalty_2 = penalty_1;
7780         let mut feerate_2 = 0;
7781         {
7782                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7783                 assert_eq!(node_txn.len(), 1);
7784                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7785                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7786                         assert_eq!(node_txn[0].output.len(), 1);
7787                         check_spends!(node_txn[0], revoked_txn[0]);
7788                         penalty_2 = node_txn[0].txid();
7789                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7790                         assert_ne!(penalty_2, penalty_1);
7791                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7792                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7793                         // Verify 25% bump heuristic
7794                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7795                         node_txn.clear();
7796                 }
7797         }
7798         assert_ne!(feerate_2, 0);
7799
7800         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7801         connect_blocks(&nodes[1], 1);
7802         let penalty_3;
7803         let mut feerate_3 = 0;
7804         {
7805                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7806                 assert_eq!(node_txn.len(), 1);
7807                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7808                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7809                         assert_eq!(node_txn[0].output.len(), 1);
7810                         check_spends!(node_txn[0], revoked_txn[0]);
7811                         penalty_3 = node_txn[0].txid();
7812                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7813                         assert_ne!(penalty_3, penalty_2);
7814                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7815                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7816                         // Verify 25% bump heuristic
7817                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7818                         node_txn.clear();
7819                 }
7820         }
7821         assert_ne!(feerate_3, 0);
7822
7823         nodes[1].node.get_and_clear_pending_events();
7824         nodes[1].node.get_and_clear_pending_msg_events();
7825 }
7826
7827 #[test]
7828 fn test_bump_penalty_txn_on_revoked_htlcs() {
7829         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7830         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7831
7832         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7833         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7834         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7835         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7836         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7837
7838         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7839         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7840         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7841         let scorer = test_utils::TestScorer::with_penalty(0);
7842         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7843         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7844                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7845         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7846         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7847         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7848                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7849         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7850
7851         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7852         assert_eq!(revoked_local_txn[0].input.len(), 1);
7853         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7854
7855         // Revoke local commitment tx
7856         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7857
7858         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7859         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7860         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7861         check_closed_broadcast!(nodes[1], true);
7862         check_added_monitors!(nodes[1], 1);
7863         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7864         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7865
7866         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7867         assert_eq!(revoked_htlc_txn.len(), 3);
7868         check_spends!(revoked_htlc_txn[1], chan.3);
7869
7870         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7871         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7872         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7873
7874         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7875         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7876         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7877         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7878
7879         // Broadcast set of revoked txn on A
7880         let hash_128 = connect_blocks(&nodes[0], 40);
7881         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7882         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7883         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7884         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7885         let events = nodes[0].node.get_and_clear_pending_events();
7886         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7887         match events.last().unwrap() {
7888                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7889                 _ => panic!("Unexpected event"),
7890         }
7891         let first;
7892         let feerate_1;
7893         let penalty_txn;
7894         {
7895                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7896                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7897                 // Verify claim tx are spending revoked HTLC txn
7898
7899                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7900                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7901                 // which are included in the same block (they are broadcasted because we scan the
7902                 // transactions linearly and generate claims as we go, they likely should be removed in the
7903                 // future).
7904                 assert_eq!(node_txn[0].input.len(), 1);
7905                 check_spends!(node_txn[0], revoked_local_txn[0]);
7906                 assert_eq!(node_txn[1].input.len(), 1);
7907                 check_spends!(node_txn[1], revoked_local_txn[0]);
7908                 assert_eq!(node_txn[2].input.len(), 1);
7909                 check_spends!(node_txn[2], revoked_local_txn[0]);
7910
7911                 // Each of the three justice transactions claim a separate (single) output of the three
7912                 // available, which we check here:
7913                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7914                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7915                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7916
7917                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7918                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7919
7920                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7921                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7922                 // a remote commitment tx has already been confirmed).
7923                 check_spends!(node_txn[3], chan.3);
7924
7925                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7926                 // output, checked above).
7927                 assert_eq!(node_txn[4].input.len(), 2);
7928                 assert_eq!(node_txn[4].output.len(), 1);
7929                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7930
7931                 first = node_txn[4].txid();
7932                 // Store both feerates for later comparison
7933                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7934                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7935                 penalty_txn = vec![node_txn[2].clone()];
7936                 node_txn.clear();
7937         }
7938
7939         // Connect one more block to see if bumped penalty are issued for HTLC txn
7940         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7941         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7942         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7943         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7944         {
7945                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7946                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7947
7948                 check_spends!(node_txn[0], revoked_local_txn[0]);
7949                 check_spends!(node_txn[1], revoked_local_txn[0]);
7950                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7951                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7952                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7953                 } else {
7954                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7955                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7956                 }
7957
7958                 node_txn.clear();
7959         };
7960
7961         // Few more blocks to confirm penalty txn
7962         connect_blocks(&nodes[0], 4);
7963         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7964         let header_144 = connect_blocks(&nodes[0], 9);
7965         let node_txn = {
7966                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7967                 assert_eq!(node_txn.len(), 1);
7968
7969                 assert_eq!(node_txn[0].input.len(), 2);
7970                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7971                 // Verify bumped tx is different and 25% bump heuristic
7972                 assert_ne!(first, node_txn[0].txid());
7973                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7974                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7975                 assert!(feerate_2 * 100 > feerate_1 * 125);
7976                 let txn = vec![node_txn[0].clone()];
7977                 node_txn.clear();
7978                 txn
7979         };
7980         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7981         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7982         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7983         connect_blocks(&nodes[0], 20);
7984         {
7985                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7986                 // We verify than no new transaction has been broadcast because previously
7987                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7988                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7989                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7990                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7991                 // up bumped justice generation.
7992                 assert_eq!(node_txn.len(), 0);
7993                 node_txn.clear();
7994         }
7995         check_closed_broadcast!(nodes[0], true);
7996         check_added_monitors!(nodes[0], 1);
7997 }
7998
7999 #[test]
8000 fn test_bump_penalty_txn_on_remote_commitment() {
8001         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
8002         // we're able to claim outputs on remote commitment transaction before timelocks expiration
8003
8004         // Create 2 HTLCs
8005         // Provide preimage for one
8006         // Check aggregation
8007
8008         let chanmon_cfgs = create_chanmon_cfgs(2);
8009         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8010         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8011         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8012
8013         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8014         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
8015         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8016
8017         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8018         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8019         assert_eq!(remote_txn[0].output.len(), 4);
8020         assert_eq!(remote_txn[0].input.len(), 1);
8021         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8022
8023         // Claim a HTLC without revocation (provide B monitor with preimage)
8024         nodes[1].node.claim_funds(payment_preimage);
8025         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
8026         mine_transaction(&nodes[1], &remote_txn[0]);
8027         check_added_monitors!(nodes[1], 2);
8028         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8029
8030         // One or more claim tx should have been broadcast, check it
8031         let timeout;
8032         let preimage;
8033         let preimage_bump;
8034         let feerate_timeout;
8035         let feerate_preimage;
8036         {
8037                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8038                 // 9 transactions including:
8039                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8040                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8041                 // 2 * HTLC-Success (one RBF bump we'll check later)
8042                 // 1 * HTLC-Timeout
8043                 assert_eq!(node_txn.len(), 8);
8044                 assert_eq!(node_txn[0].input.len(), 1);
8045                 assert_eq!(node_txn[6].input.len(), 1);
8046                 check_spends!(node_txn[0], remote_txn[0]);
8047                 check_spends!(node_txn[6], remote_txn[0]);
8048
8049                 check_spends!(node_txn[1], chan.3);
8050                 check_spends!(node_txn[2], node_txn[1]);
8051
8052                 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
8053                         preimage_bump = node_txn[3].clone();
8054                         check_spends!(node_txn[3], remote_txn[0]);
8055
8056                         assert_eq!(node_txn[1], node_txn[4]);
8057                         assert_eq!(node_txn[2], node_txn[5]);
8058                 } else {
8059                         preimage_bump = node_txn[7].clone();
8060                         check_spends!(node_txn[7], remote_txn[0]);
8061                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8062
8063                         assert_eq!(node_txn[1], node_txn[3]);
8064                         assert_eq!(node_txn[2], node_txn[4]);
8065                 }
8066
8067                 timeout = node_txn[6].txid();
8068                 let index = node_txn[6].input[0].previous_output.vout;
8069                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8070                 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8071
8072                 preimage = node_txn[0].txid();
8073                 let index = node_txn[0].input[0].previous_output.vout;
8074                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8075                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8076
8077                 node_txn.clear();
8078         };
8079         assert_ne!(feerate_timeout, 0);
8080         assert_ne!(feerate_preimage, 0);
8081
8082         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8083         connect_blocks(&nodes[1], 15);
8084         {
8085                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8086                 assert_eq!(node_txn.len(), 1);
8087                 assert_eq!(node_txn[0].input.len(), 1);
8088                 assert_eq!(preimage_bump.input.len(), 1);
8089                 check_spends!(node_txn[0], remote_txn[0]);
8090                 check_spends!(preimage_bump, remote_txn[0]);
8091
8092                 let index = preimage_bump.input[0].previous_output.vout;
8093                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8094                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8095                 assert!(new_feerate * 100 > feerate_timeout * 125);
8096                 assert_ne!(timeout, preimage_bump.txid());
8097
8098                 let index = node_txn[0].input[0].previous_output.vout;
8099                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8100                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8101                 assert!(new_feerate * 100 > feerate_preimage * 125);
8102                 assert_ne!(preimage, node_txn[0].txid());
8103
8104                 node_txn.clear();
8105         }
8106
8107         nodes[1].node.get_and_clear_pending_events();
8108         nodes[1].node.get_and_clear_pending_msg_events();
8109 }
8110
8111 #[test]
8112 fn test_counterparty_raa_skip_no_crash() {
8113         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8114         // commitment transaction, we would have happily carried on and provided them the next
8115         // commitment transaction based on one RAA forward. This would probably eventually have led to
8116         // channel closure, but it would not have resulted in funds loss. Still, our
8117         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8118         // check simply that the channel is closed in response to such an RAA, but don't check whether
8119         // we decide to punish our counterparty for revoking their funds (as we don't currently
8120         // implement that).
8121         let chanmon_cfgs = create_chanmon_cfgs(2);
8122         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8123         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8124         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8125         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8126
8127         let per_commitment_secret;
8128         let next_per_commitment_point;
8129         {
8130                 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8131                 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8132
8133                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8134
8135                 // Make signer believe we got a counterparty signature, so that it allows the revocation
8136                 keys.get_enforcement_state().last_holder_commitment -= 1;
8137                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8138
8139                 // Must revoke without gaps
8140                 keys.get_enforcement_state().last_holder_commitment -= 1;
8141                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8142
8143                 keys.get_enforcement_state().last_holder_commitment -= 1;
8144                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8145                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8146         }
8147
8148         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8149                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8150         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8151         check_added_monitors!(nodes[1], 1);
8152         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8153 }
8154
8155 #[test]
8156 fn test_bump_txn_sanitize_tracking_maps() {
8157         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8158         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8159
8160         let chanmon_cfgs = create_chanmon_cfgs(2);
8161         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8162         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8163         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8164
8165         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8166         // Lock HTLC in both directions
8167         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
8168         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
8169
8170         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8171         assert_eq!(revoked_local_txn[0].input.len(), 1);
8172         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8173
8174         // Revoke local commitment tx
8175         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
8176
8177         // Broadcast set of revoked txn on A
8178         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8179         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
8180         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8181
8182         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8183         check_closed_broadcast!(nodes[0], true);
8184         check_added_monitors!(nodes[0], 1);
8185         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8186         let penalty_txn = {
8187                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8188                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8189                 check_spends!(node_txn[0], revoked_local_txn[0]);
8190                 check_spends!(node_txn[1], revoked_local_txn[0]);
8191                 check_spends!(node_txn[2], revoked_local_txn[0]);
8192                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8193                 node_txn.clear();
8194                 penalty_txn
8195         };
8196         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8197         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8198         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8199         {
8200                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8201                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8202                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8203         }
8204 }
8205
8206 #[test]
8207 fn test_pending_claimed_htlc_no_balance_underflow() {
8208         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8209         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8210         let chanmon_cfgs = create_chanmon_cfgs(2);
8211         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8212         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8213         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8214         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8215
8216         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8217         nodes[1].node.claim_funds(payment_preimage);
8218         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8219         check_added_monitors!(nodes[1], 1);
8220         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8221
8222         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8223         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8224         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8225         check_added_monitors!(nodes[0], 1);
8226         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8227
8228         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8229         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8230         // can get our balance.
8231
8232         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8233         // the public key of the only hop. This works around ChannelDetails not showing the
8234         // almost-claimed HTLC as available balance.
8235         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8236         route.payment_params = None; // This is all wrong, but unnecessary
8237         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8238         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8239         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8240
8241         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8242 }
8243
8244 #[test]
8245 fn test_channel_conf_timeout() {
8246         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8247         // confirm within 2016 blocks, as recommended by BOLT 2.
8248         let chanmon_cfgs = create_chanmon_cfgs(2);
8249         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8250         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8251         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8252
8253         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8254
8255         // The outbound node should wait forever for confirmation:
8256         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8257         // copied here instead of directly referencing the constant.
8258         connect_blocks(&nodes[0], 2016);
8259         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8260
8261         // The inbound node should fail the channel after exactly 2016 blocks
8262         connect_blocks(&nodes[1], 2015);
8263         check_added_monitors!(nodes[1], 0);
8264         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8265
8266         connect_blocks(&nodes[1], 1);
8267         check_added_monitors!(nodes[1], 1);
8268         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8269         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8270         assert_eq!(close_ev.len(), 1);
8271         match close_ev[0] {
8272                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8273                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8274                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8275                 },
8276                 _ => panic!("Unexpected event"),
8277         }
8278 }
8279
8280 #[test]
8281 fn test_override_channel_config() {
8282         let chanmon_cfgs = create_chanmon_cfgs(2);
8283         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8284         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8285         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8286
8287         // Node0 initiates a channel to node1 using the override config.
8288         let mut override_config = UserConfig::default();
8289         override_config.channel_handshake_config.our_to_self_delay = 200;
8290
8291         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8292
8293         // Assert the channel created by node0 is using the override config.
8294         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8295         assert_eq!(res.channel_flags, 0);
8296         assert_eq!(res.to_self_delay, 200);
8297 }
8298
8299 #[test]
8300 fn test_override_0msat_htlc_minimum() {
8301         let mut zero_config = UserConfig::default();
8302         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8303         let chanmon_cfgs = create_chanmon_cfgs(2);
8304         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8305         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8306         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8307
8308         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8309         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8310         assert_eq!(res.htlc_minimum_msat, 1);
8311
8312         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8313         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8314         assert_eq!(res.htlc_minimum_msat, 1);
8315 }
8316
8317 #[test]
8318 fn test_channel_update_has_correct_htlc_maximum_msat() {
8319         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8320         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8321         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8322         // 90% of the `channel_value`.
8323         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8324
8325         let mut config_30_percent = UserConfig::default();
8326         config_30_percent.channel_handshake_config.announced_channel = true;
8327         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8328         let mut config_50_percent = UserConfig::default();
8329         config_50_percent.channel_handshake_config.announced_channel = true;
8330         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8331         let mut config_95_percent = UserConfig::default();
8332         config_95_percent.channel_handshake_config.announced_channel = true;
8333         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8334         let mut config_100_percent = UserConfig::default();
8335         config_100_percent.channel_handshake_config.announced_channel = true;
8336         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8337
8338         let chanmon_cfgs = create_chanmon_cfgs(4);
8339         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8340         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)]);
8341         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8342
8343         let channel_value_satoshis = 100000;
8344         let channel_value_msat = channel_value_satoshis * 1000;
8345         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8346         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8347         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8348
8349         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());
8350         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());
8351
8352         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8353         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8354         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
8355         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8356         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8357         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
8358
8359         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8360         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8361         // `channel_value`.
8362         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8363         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8364         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8365         // `channel_value`.
8366         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8367 }
8368
8369 #[test]
8370 fn test_manually_accept_inbound_channel_request() {
8371         let mut manually_accept_conf = UserConfig::default();
8372         manually_accept_conf.manually_accept_inbound_channels = true;
8373         let chanmon_cfgs = create_chanmon_cfgs(2);
8374         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8375         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8376         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8377
8378         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8379         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8380
8381         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8382
8383         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8384         // accepting the inbound channel request.
8385         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8386
8387         let events = nodes[1].node.get_and_clear_pending_events();
8388         match events[0] {
8389                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8390                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8391                 }
8392                 _ => panic!("Unexpected event"),
8393         }
8394
8395         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8396         assert_eq!(accept_msg_ev.len(), 1);
8397
8398         match accept_msg_ev[0] {
8399                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8400                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8401                 }
8402                 _ => panic!("Unexpected event"),
8403         }
8404
8405         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8406
8407         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8408         assert_eq!(close_msg_ev.len(), 1);
8409
8410         let events = nodes[1].node.get_and_clear_pending_events();
8411         match events[0] {
8412                 Event::ChannelClosed { user_channel_id, .. } => {
8413                         assert_eq!(user_channel_id, 23);
8414                 }
8415                 _ => panic!("Unexpected event"),
8416         }
8417 }
8418
8419 #[test]
8420 fn test_manually_reject_inbound_channel_request() {
8421         let mut manually_accept_conf = UserConfig::default();
8422         manually_accept_conf.manually_accept_inbound_channels = true;
8423         let chanmon_cfgs = create_chanmon_cfgs(2);
8424         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8425         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8426         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8427
8428         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8429         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8430
8431         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8432
8433         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8434         // rejecting the inbound channel request.
8435         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8436
8437         let events = nodes[1].node.get_and_clear_pending_events();
8438         match events[0] {
8439                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8440                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8441                 }
8442                 _ => panic!("Unexpected event"),
8443         }
8444
8445         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8446         assert_eq!(close_msg_ev.len(), 1);
8447
8448         match close_msg_ev[0] {
8449                 MessageSendEvent::HandleError { ref node_id, .. } => {
8450                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8451                 }
8452                 _ => panic!("Unexpected event"),
8453         }
8454         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8455 }
8456
8457 #[test]
8458 fn test_reject_funding_before_inbound_channel_accepted() {
8459         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8460         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8461         // the node operator before the counterparty sends a `FundingCreated` message. If a
8462         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8463         // and the channel should be closed.
8464         let mut manually_accept_conf = UserConfig::default();
8465         manually_accept_conf.manually_accept_inbound_channels = true;
8466         let chanmon_cfgs = create_chanmon_cfgs(2);
8467         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8468         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8469         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8470
8471         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8472         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8473         let temp_channel_id = res.temporary_channel_id;
8474
8475         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8476
8477         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8478         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8479
8480         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8481         nodes[1].node.get_and_clear_pending_events();
8482
8483         // Get the `AcceptChannel` message of `nodes[1]` without calling
8484         // `ChannelManager::accept_inbound_channel`, which generates a
8485         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8486         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8487         // succeed when `nodes[0]` is passed to it.
8488         let accept_chan_msg = {
8489                 let mut lock;
8490                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8491                 channel.get_accept_channel_message()
8492         };
8493         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8494
8495         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8496
8497         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8498         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8499
8500         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8501         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8502
8503         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8504         assert_eq!(close_msg_ev.len(), 1);
8505
8506         let expected_err = "FundingCreated message received before the channel was accepted";
8507         match close_msg_ev[0] {
8508                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8509                         assert_eq!(msg.channel_id, temp_channel_id);
8510                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8511                         assert_eq!(msg.data, expected_err);
8512                 }
8513                 _ => panic!("Unexpected event"),
8514         }
8515
8516         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8517 }
8518
8519 #[test]
8520 fn test_can_not_accept_inbound_channel_twice() {
8521         let mut manually_accept_conf = UserConfig::default();
8522         manually_accept_conf.manually_accept_inbound_channels = true;
8523         let chanmon_cfgs = create_chanmon_cfgs(2);
8524         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8525         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8526         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8527
8528         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8529         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8530
8531         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8532
8533         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8534         // accepting the inbound channel request.
8535         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8536
8537         let events = nodes[1].node.get_and_clear_pending_events();
8538         match events[0] {
8539                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8540                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8541                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8542                         match api_res {
8543                                 Err(APIError::APIMisuseError { err }) => {
8544                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8545                                 },
8546                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8547                                 Err(_) => panic!("Unexpected Error"),
8548                         }
8549                 }
8550                 _ => panic!("Unexpected event"),
8551         }
8552
8553         // Ensure that the channel wasn't closed after attempting to accept it twice.
8554         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8555         assert_eq!(accept_msg_ev.len(), 1);
8556
8557         match accept_msg_ev[0] {
8558                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8559                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8560                 }
8561                 _ => panic!("Unexpected event"),
8562         }
8563 }
8564
8565 #[test]
8566 fn test_can_not_accept_unknown_inbound_channel() {
8567         let chanmon_cfg = create_chanmon_cfgs(2);
8568         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8569         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8570         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8571
8572         let unknown_channel_id = [0; 32];
8573         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8574         match api_res {
8575                 Err(APIError::ChannelUnavailable { err }) => {
8576                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8577                 },
8578                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8579                 Err(_) => panic!("Unexpected Error"),
8580         }
8581 }
8582
8583 #[test]
8584 fn test_simple_mpp() {
8585         // Simple test of sending a multi-path payment.
8586         let chanmon_cfgs = create_chanmon_cfgs(4);
8587         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8588         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8589         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8590
8591         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8592         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8593         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8594         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8595
8596         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8597         let path = route.paths[0].clone();
8598         route.paths.push(path);
8599         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8600         route.paths[0][0].short_channel_id = chan_1_id;
8601         route.paths[0][1].short_channel_id = chan_3_id;
8602         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8603         route.paths[1][0].short_channel_id = chan_2_id;
8604         route.paths[1][1].short_channel_id = chan_4_id;
8605         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8606         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8607 }
8608
8609 #[test]
8610 fn test_preimage_storage() {
8611         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8612         let chanmon_cfgs = create_chanmon_cfgs(2);
8613         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8614         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8615         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8616
8617         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8618
8619         {
8620                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8621                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8622                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8623                 check_added_monitors!(nodes[0], 1);
8624                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8625                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8626                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8627                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8628         }
8629         // Note that after leaving the above scope we have no knowledge of any arguments or return
8630         // values from previous calls.
8631         expect_pending_htlcs_forwardable!(nodes[1]);
8632         let events = nodes[1].node.get_and_clear_pending_events();
8633         assert_eq!(events.len(), 1);
8634         match events[0] {
8635                 Event::PaymentReceived { ref purpose, .. } => {
8636                         match &purpose {
8637                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8638                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8639                                 },
8640                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8641                         }
8642                 },
8643                 _ => panic!("Unexpected event"),
8644         }
8645 }
8646
8647 #[test]
8648 #[allow(deprecated)]
8649 fn test_secret_timeout() {
8650         // Simple test of payment secret storage time outs. After
8651         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8652         let chanmon_cfgs = create_chanmon_cfgs(2);
8653         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8654         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8655         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8656
8657         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8658
8659         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8660
8661         // We should fail to register the same payment hash twice, at least until we've connected a
8662         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8663         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8664                 assert_eq!(err, "Duplicate payment hash");
8665         } else { panic!(); }
8666         let mut block = {
8667                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8668                 Block {
8669                         header: BlockHeader {
8670                                 version: 0x2000000,
8671                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8672                                 merkle_root: Default::default(),
8673                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8674                         txdata: vec![],
8675                 }
8676         };
8677         connect_block(&nodes[1], &block);
8678         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8679                 assert_eq!(err, "Duplicate payment hash");
8680         } else { panic!(); }
8681
8682         // If we then connect the second block, we should be able to register the same payment hash
8683         // again (this time getting a new payment secret).
8684         block.header.prev_blockhash = block.header.block_hash();
8685         block.header.time += 1;
8686         connect_block(&nodes[1], &block);
8687         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8688         assert_ne!(payment_secret_1, our_payment_secret);
8689
8690         {
8691                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8692                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8693                 check_added_monitors!(nodes[0], 1);
8694                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8695                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8696                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8697                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8698         }
8699         // Note that after leaving the above scope we have no knowledge of any arguments or return
8700         // values from previous calls.
8701         expect_pending_htlcs_forwardable!(nodes[1]);
8702         let events = nodes[1].node.get_and_clear_pending_events();
8703         assert_eq!(events.len(), 1);
8704         match events[0] {
8705                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8706                         assert!(payment_preimage.is_none());
8707                         assert_eq!(payment_secret, our_payment_secret);
8708                         // We don't actually have the payment preimage with which to claim this payment!
8709                 },
8710                 _ => panic!("Unexpected event"),
8711         }
8712 }
8713
8714 #[test]
8715 fn test_bad_secret_hash() {
8716         // Simple test of unregistered payment hash/invalid payment secret handling
8717         let chanmon_cfgs = create_chanmon_cfgs(2);
8718         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8719         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8720         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8721
8722         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8723
8724         let random_payment_hash = PaymentHash([42; 32]);
8725         let random_payment_secret = PaymentSecret([43; 32]);
8726         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8727         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8728
8729         // All the below cases should end up being handled exactly identically, so we macro the
8730         // resulting events.
8731         macro_rules! handle_unknown_invalid_payment_data {
8732                 ($payment_hash: expr) => {
8733                         check_added_monitors!(nodes[0], 1);
8734                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8735                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8736                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8737                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8738
8739                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8740                         // again to process the pending backwards-failure of the HTLC
8741                         expect_pending_htlcs_forwardable!(nodes[1]);
8742                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8743                         check_added_monitors!(nodes[1], 1);
8744
8745                         // We should fail the payment back
8746                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8747                         match events.pop().unwrap() {
8748                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8749                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8750                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8751                                 },
8752                                 _ => panic!("Unexpected event"),
8753                         }
8754                 }
8755         }
8756
8757         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8758         // Error data is the HTLC value (100,000) and current block height
8759         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8760
8761         // Send a payment with the right payment hash but the wrong payment secret
8762         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8763         handle_unknown_invalid_payment_data!(our_payment_hash);
8764         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8765
8766         // Send a payment with a random payment hash, but the right payment secret
8767         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8768         handle_unknown_invalid_payment_data!(random_payment_hash);
8769         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8770
8771         // Send a payment with a random payment hash and random payment secret
8772         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8773         handle_unknown_invalid_payment_data!(random_payment_hash);
8774         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8775 }
8776
8777 #[test]
8778 fn test_update_err_monitor_lockdown() {
8779         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8780         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8781         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8782         //
8783         // This scenario may happen in a watchtower setup, where watchtower process a block height
8784         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8785         // commitment at same time.
8786
8787         let chanmon_cfgs = create_chanmon_cfgs(2);
8788         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8789         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8790         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8791
8792         // Create some initial channel
8793         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8794         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8795
8796         // Rebalance the network to generate htlc in the two directions
8797         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8798
8799         // Route a HTLC from node 0 to node 1 (but don't settle)
8800         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8801
8802         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8803         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8804         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8805         let persister = test_utils::TestPersister::new();
8806         let watchtower = {
8807                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8808                 let mut w = test_utils::TestVecWriter(Vec::new());
8809                 monitor.write(&mut w).unwrap();
8810                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8811                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8812                 assert!(new_monitor == *monitor);
8813                 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);
8814                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8815                 watchtower
8816         };
8817         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8818         let block = Block { header, txdata: vec![] };
8819         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8820         // transaction lock time requirements here.
8821         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8822         watchtower.chain_monitor.block_connected(&block, 200);
8823
8824         // Try to update ChannelMonitor
8825         nodes[1].node.claim_funds(preimage);
8826         check_added_monitors!(nodes[1], 1);
8827         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8828
8829         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8830         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8831         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8832         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8833                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8834                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8835                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8836                 } else { assert!(false); }
8837         } else { assert!(false); };
8838         // Our local monitor is in-sync and hasn't processed yet timeout
8839         check_added_monitors!(nodes[0], 1);
8840         let events = nodes[0].node.get_and_clear_pending_events();
8841         assert_eq!(events.len(), 1);
8842 }
8843
8844 #[test]
8845 fn test_concurrent_monitor_claim() {
8846         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8847         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8848         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8849         // state N+1 confirms. Alice claims output from state N+1.
8850
8851         let chanmon_cfgs = create_chanmon_cfgs(2);
8852         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8853         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8854         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8855
8856         // Create some initial channel
8857         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8858         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8859
8860         // Rebalance the network to generate htlc in the two directions
8861         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8862
8863         // Route a HTLC from node 0 to node 1 (but don't settle)
8864         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8865
8866         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8867         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8868         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8869         let persister = test_utils::TestPersister::new();
8870         let watchtower_alice = {
8871                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8872                 let mut w = test_utils::TestVecWriter(Vec::new());
8873                 monitor.write(&mut w).unwrap();
8874                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8875                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8876                 assert!(new_monitor == *monitor);
8877                 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);
8878                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8879                 watchtower
8880         };
8881         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8882         let block = Block { header, txdata: vec![] };
8883         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8884         // transaction lock time requirements here.
8885         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));
8886         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8887
8888         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8889         {
8890                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8891                 assert_eq!(txn.len(), 2);
8892                 txn.clear();
8893         }
8894
8895         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8896         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8897         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8898         let persister = test_utils::TestPersister::new();
8899         let watchtower_bob = {
8900                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8901                 let mut w = test_utils::TestVecWriter(Vec::new());
8902                 monitor.write(&mut w).unwrap();
8903                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8904                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8905                 assert!(new_monitor == *monitor);
8906                 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);
8907                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8908                 watchtower
8909         };
8910         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8911         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8912
8913         // Route another payment to generate another update with still previous HTLC pending
8914         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8915         {
8916                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8917         }
8918         check_added_monitors!(nodes[1], 1);
8919
8920         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8921         assert_eq!(updates.update_add_htlcs.len(), 1);
8922         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8923         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8924                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8925                         // Watchtower Alice should already have seen the block and reject the update
8926                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8927                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8928                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8929                 } else { assert!(false); }
8930         } else { assert!(false); };
8931         // Our local monitor is in-sync and hasn't processed yet timeout
8932         check_added_monitors!(nodes[0], 1);
8933
8934         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8935         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8936         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8937
8938         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8939         let bob_state_y;
8940         {
8941                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8942                 assert_eq!(txn.len(), 2);
8943                 bob_state_y = txn[0].clone();
8944                 txn.clear();
8945         };
8946
8947         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8948         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8949         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);
8950         {
8951                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8952                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8953                 // the onchain detection of the HTLC output
8954                 assert_eq!(htlc_txn.len(), 2);
8955                 check_spends!(htlc_txn[0], bob_state_y);
8956                 check_spends!(htlc_txn[1], bob_state_y);
8957         }
8958 }
8959
8960 #[test]
8961 fn test_pre_lockin_no_chan_closed_update() {
8962         // Test that if a peer closes a channel in response to a funding_created message we don't
8963         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8964         // message).
8965         //
8966         // Doing so would imply a channel monitor update before the initial channel monitor
8967         // registration, violating our API guarantees.
8968         //
8969         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8970         // then opening a second channel with the same funding output as the first (which is not
8971         // rejected because the first channel does not exist in the ChannelManager) and closing it
8972         // before receiving funding_signed.
8973         let chanmon_cfgs = create_chanmon_cfgs(2);
8974         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8975         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8976         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8977
8978         // Create an initial channel
8979         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8980         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8981         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8982         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8983         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8984
8985         // Move the first channel through the funding flow...
8986         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8987
8988         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8989         check_added_monitors!(nodes[0], 0);
8990
8991         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8992         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8993         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8994         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8995         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8996 }
8997
8998 #[test]
8999 fn test_htlc_no_detection() {
9000         // This test is a mutation to underscore the detection logic bug we had
9001         // before #653. HTLC value routed is above the remaining balance, thus
9002         // inverting HTLC and `to_remote` output. HTLC will come second and
9003         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
9004         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
9005         // outputs order detection for correct spending children filtring.
9006
9007         let chanmon_cfgs = create_chanmon_cfgs(2);
9008         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9009         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9010         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9011
9012         // Create some initial channels
9013         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9014
9015         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
9016         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
9017         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
9018         assert_eq!(local_txn[0].input.len(), 1);
9019         assert_eq!(local_txn[0].output.len(), 3);
9020         check_spends!(local_txn[0], chan_1.3);
9021
9022         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9023         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9024         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
9025         // We deliberately connect the local tx twice as this should provoke a failure calling
9026         // this test before #653 fix.
9027         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);
9028         check_closed_broadcast!(nodes[0], true);
9029         check_added_monitors!(nodes[0], 1);
9030         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
9031         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9032
9033         let htlc_timeout = {
9034                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9035                 assert_eq!(node_txn[1].input.len(), 1);
9036                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9037                 check_spends!(node_txn[1], local_txn[0]);
9038                 node_txn[1].clone()
9039         };
9040
9041         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9042         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9043         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9044         expect_payment_failed!(nodes[0], our_payment_hash, true);
9045 }
9046
9047 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9048         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9049         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9050         // Carol, Alice would be the upstream node, and Carol the downstream.)
9051         //
9052         // Steps of the test:
9053         // 1) Alice sends a HTLC to Carol through Bob.
9054         // 2) Carol doesn't settle the HTLC.
9055         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9056         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9057         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9058         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9059         // 5) Carol release the preimage to Bob off-chain.
9060         // 6) Bob claims the offered output on the broadcasted commitment.
9061         let chanmon_cfgs = create_chanmon_cfgs(3);
9062         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9063         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9064         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9065
9066         // Create some initial channels
9067         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9068         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9069
9070         // Steps (1) and (2):
9071         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9072         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9073
9074         // Check that Alice's commitment transaction now contains an output for this HTLC.
9075         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9076         check_spends!(alice_txn[0], chan_ab.3);
9077         assert_eq!(alice_txn[0].output.len(), 2);
9078         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9079         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9080         assert_eq!(alice_txn.len(), 2);
9081
9082         // Steps (3) and (4):
9083         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9084         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9085         let mut force_closing_node = 0; // Alice force-closes
9086         let mut counterparty_node = 1; // Bob if Alice force-closes
9087
9088         // Bob force-closes
9089         if !broadcast_alice {
9090                 force_closing_node = 1;
9091                 counterparty_node = 0;
9092         }
9093         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9094         check_closed_broadcast!(nodes[force_closing_node], true);
9095         check_added_monitors!(nodes[force_closing_node], 1);
9096         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9097         if go_onchain_before_fulfill {
9098                 let txn_to_broadcast = match broadcast_alice {
9099                         true => alice_txn.clone(),
9100                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9101                 };
9102                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9103                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9104                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9105                 if broadcast_alice {
9106                         check_closed_broadcast!(nodes[1], true);
9107                         check_added_monitors!(nodes[1], 1);
9108                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9109                 }
9110                 assert_eq!(bob_txn.len(), 1);
9111                 check_spends!(bob_txn[0], chan_ab.3);
9112         }
9113
9114         // Step (5):
9115         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9116         // process of removing the HTLC from their commitment transactions.
9117         nodes[2].node.claim_funds(payment_preimage);
9118         check_added_monitors!(nodes[2], 1);
9119         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9120
9121         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9122         assert!(carol_updates.update_add_htlcs.is_empty());
9123         assert!(carol_updates.update_fail_htlcs.is_empty());
9124         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9125         assert!(carol_updates.update_fee.is_none());
9126         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9127
9128         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9129         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9130         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9131         if !go_onchain_before_fulfill && broadcast_alice {
9132                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9133                 assert_eq!(events.len(), 1);
9134                 match events[0] {
9135                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9136                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9137                         },
9138                         _ => panic!("Unexpected event"),
9139                 };
9140         }
9141         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9142         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9143         // Carol<->Bob's updated commitment transaction info.
9144         check_added_monitors!(nodes[1], 2);
9145
9146         let events = nodes[1].node.get_and_clear_pending_msg_events();
9147         assert_eq!(events.len(), 2);
9148         let bob_revocation = match events[0] {
9149                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9150                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9151                         (*msg).clone()
9152                 },
9153                 _ => panic!("Unexpected event"),
9154         };
9155         let bob_updates = match events[1] {
9156                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9157                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9158                         (*updates).clone()
9159                 },
9160                 _ => panic!("Unexpected event"),
9161         };
9162
9163         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9164         check_added_monitors!(nodes[2], 1);
9165         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9166         check_added_monitors!(nodes[2], 1);
9167
9168         let events = nodes[2].node.get_and_clear_pending_msg_events();
9169         assert_eq!(events.len(), 1);
9170         let carol_revocation = match events[0] {
9171                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9172                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9173                         (*msg).clone()
9174                 },
9175                 _ => panic!("Unexpected event"),
9176         };
9177         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9178         check_added_monitors!(nodes[1], 1);
9179
9180         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9181         // here's where we put said channel's commitment tx on-chain.
9182         let mut txn_to_broadcast = alice_txn.clone();
9183         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9184         if !go_onchain_before_fulfill {
9185                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9186                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9187                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9188                 if broadcast_alice {
9189                         check_closed_broadcast!(nodes[1], true);
9190                         check_added_monitors!(nodes[1], 1);
9191                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9192                 }
9193                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9194                 if broadcast_alice {
9195                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9196                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9197                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9198                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9199                         // broadcasted.
9200                         assert_eq!(bob_txn.len(), 3);
9201                         check_spends!(bob_txn[1], chan_ab.3);
9202                 } else {
9203                         assert_eq!(bob_txn.len(), 2);
9204                         check_spends!(bob_txn[0], chan_ab.3);
9205                 }
9206         }
9207
9208         // Step (6):
9209         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9210         // broadcasted commitment transaction.
9211         {
9212                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9213                 if go_onchain_before_fulfill {
9214                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9215                         assert_eq!(bob_txn.len(), 2);
9216                 }
9217                 let script_weight = match broadcast_alice {
9218                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9219                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9220                 };
9221                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9222                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9223                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9224                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9225                 if broadcast_alice && !go_onchain_before_fulfill {
9226                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9227                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9228                 } else {
9229                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9230                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9231                 }
9232         }
9233 }
9234
9235 #[test]
9236 fn test_onchain_htlc_settlement_after_close() {
9237         do_test_onchain_htlc_settlement_after_close(true, true);
9238         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9239         do_test_onchain_htlc_settlement_after_close(true, false);
9240         do_test_onchain_htlc_settlement_after_close(false, false);
9241 }
9242
9243 #[test]
9244 fn test_duplicate_chan_id() {
9245         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9246         // already open we reject it and keep the old channel.
9247         //
9248         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9249         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9250         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9251         // updating logic for the existing channel.
9252         let chanmon_cfgs = create_chanmon_cfgs(2);
9253         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9254         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9255         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9256
9257         // Create an initial channel
9258         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9259         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9260         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9261         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()));
9262
9263         // Try to create a second channel with the same temporary_channel_id as the first and check
9264         // that it is rejected.
9265         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9266         {
9267                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9268                 assert_eq!(events.len(), 1);
9269                 match events[0] {
9270                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9271                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9272                                 // first (valid) and second (invalid) channels are closed, given they both have
9273                                 // the same non-temporary channel_id. However, currently we do not, so we just
9274                                 // move forward with it.
9275                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9276                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9277                         },
9278                         _ => panic!("Unexpected event"),
9279                 }
9280         }
9281
9282         // Move the first channel through the funding flow...
9283         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9284
9285         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9286         check_added_monitors!(nodes[0], 0);
9287
9288         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9289         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9290         {
9291                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9292                 assert_eq!(added_monitors.len(), 1);
9293                 assert_eq!(added_monitors[0].0, funding_output);
9294                 added_monitors.clear();
9295         }
9296         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9297
9298         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9299         let channel_id = funding_outpoint.to_channel_id();
9300
9301         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9302         // temporary one).
9303
9304         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9305         // Technically this is allowed by the spec, but we don't support it and there's little reason
9306         // to. Still, it shouldn't cause any other issues.
9307         open_chan_msg.temporary_channel_id = channel_id;
9308         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9309         {
9310                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9311                 assert_eq!(events.len(), 1);
9312                 match events[0] {
9313                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9314                                 // Technically, at this point, nodes[1] would be justified in thinking both
9315                                 // channels are closed, but currently we do not, so we just move forward with it.
9316                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9317                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9318                         },
9319                         _ => panic!("Unexpected event"),
9320                 }
9321         }
9322
9323         // Now try to create a second channel which has a duplicate funding output.
9324         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9325         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9326         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9327         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()));
9328         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9329
9330         let funding_created = {
9331                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9332                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9333                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9334                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9335                 // channelmanager in a possibly nonsense state instead).
9336                 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9337                 let logger = test_utils::TestLogger::new();
9338                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9339         };
9340         check_added_monitors!(nodes[0], 0);
9341         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9342         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9343         // still needs to be cleared here.
9344         check_added_monitors!(nodes[1], 1);
9345
9346         // ...still, nodes[1] will reject the duplicate channel.
9347         {
9348                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9349                 assert_eq!(events.len(), 1);
9350                 match events[0] {
9351                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9352                                 // Technically, at this point, nodes[1] would be justified in thinking both
9353                                 // channels are closed, but currently we do not, so we just move forward with it.
9354                                 assert_eq!(msg.channel_id, channel_id);
9355                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9356                         },
9357                         _ => panic!("Unexpected event"),
9358                 }
9359         }
9360
9361         // finally, finish creating the original channel and send a payment over it to make sure
9362         // everything is functional.
9363         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9364         {
9365                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9366                 assert_eq!(added_monitors.len(), 1);
9367                 assert_eq!(added_monitors[0].0, funding_output);
9368                 added_monitors.clear();
9369         }
9370
9371         let events_4 = nodes[0].node.get_and_clear_pending_events();
9372         assert_eq!(events_4.len(), 0);
9373         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9374         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9375
9376         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9377         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9378         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9379         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9380 }
9381
9382 #[test]
9383 fn test_error_chans_closed() {
9384         // Test that we properly handle error messages, closing appropriate channels.
9385         //
9386         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9387         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9388         // we can test various edge cases around it to ensure we don't regress.
9389         let chanmon_cfgs = create_chanmon_cfgs(3);
9390         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9391         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9392         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9393
9394         // Create some initial channels
9395         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9396         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9397         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9398
9399         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9400         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9401         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9402
9403         // Closing a channel from a different peer has no effect
9404         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9405         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9406
9407         // Closing one channel doesn't impact others
9408         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9409         check_added_monitors!(nodes[0], 1);
9410         check_closed_broadcast!(nodes[0], false);
9411         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9412         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9413         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9414         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);
9415         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);
9416
9417         // A null channel ID should close all channels
9418         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9419         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9420         check_added_monitors!(nodes[0], 2);
9421         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9422         let events = nodes[0].node.get_and_clear_pending_msg_events();
9423         assert_eq!(events.len(), 2);
9424         match events[0] {
9425                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9426                         assert_eq!(msg.contents.flags & 2, 2);
9427                 },
9428                 _ => panic!("Unexpected event"),
9429         }
9430         match events[1] {
9431                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9432                         assert_eq!(msg.contents.flags & 2, 2);
9433                 },
9434                 _ => panic!("Unexpected event"),
9435         }
9436         // Note that at this point users of a standard PeerHandler will end up calling
9437         // peer_disconnected with no_connection_possible set to false, duplicating the
9438         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9439         // users with their own peer handling logic. We duplicate the call here, however.
9440         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9441         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9442
9443         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9444         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9445         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9446 }
9447
9448 #[test]
9449 fn test_invalid_funding_tx() {
9450         // Test that we properly handle invalid funding transactions sent to us from a peer.
9451         //
9452         // Previously, all other major lightning implementations had failed to properly sanitize
9453         // funding transactions from their counterparties, leading to a multi-implementation critical
9454         // security vulnerability (though we always sanitized properly, we've previously had
9455         // un-released crashes in the sanitization process).
9456         //
9457         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9458         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9459         // gave up on it. We test this here by generating such a transaction.
9460         let chanmon_cfgs = create_chanmon_cfgs(2);
9461         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9462         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9463         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9464
9465         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9466         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()));
9467         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()));
9468
9469         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9470
9471         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9472         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9473         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9474         // its length.
9475         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9476         assert!(chan_utils::HTLCType::scriptlen_to_htlctype(wit_program.len()).unwrap() ==
9477                 chan_utils::HTLCType::AcceptedHTLC);
9478
9479         let wit_program_script: Script = wit_program.clone().into();
9480         for output in tx.output.iter_mut() {
9481                 // Make the confirmed funding transaction have a bogus script_pubkey
9482                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9483         }
9484
9485         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9486         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()));
9487         check_added_monitors!(nodes[1], 1);
9488
9489         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()));
9490         check_added_monitors!(nodes[0], 1);
9491
9492         let events_1 = nodes[0].node.get_and_clear_pending_events();
9493         assert_eq!(events_1.len(), 0);
9494
9495         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9496         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9497         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9498
9499         let expected_err = "funding tx had wrong script/value or output index";
9500         confirm_transaction_at(&nodes[1], &tx, 1);
9501         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9502         check_added_monitors!(nodes[1], 1);
9503         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9504         assert_eq!(events_2.len(), 1);
9505         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9506                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9507                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9508                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9509                 } else { panic!(); }
9510         } else { panic!(); }
9511         assert_eq!(nodes[1].node.list_channels().len(), 0);
9512
9513         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9514         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9515         // as its not 32 bytes long.
9516         let mut spend_tx = Transaction {
9517                 version: 2i32, lock_time: 0,
9518                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9519                         previous_output: BitcoinOutPoint {
9520                                 txid: tx.txid(),
9521                                 vout: idx as u32,
9522                         },
9523                         script_sig: Script::new(),
9524                         sequence: 0xfffffffd,
9525                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9526                 }).collect(),
9527                 output: vec![TxOut {
9528                         value: 1000,
9529                         script_pubkey: Script::new(),
9530                 }]
9531         };
9532         check_spends!(spend_tx, tx);
9533         mine_transaction(&nodes[1], &spend_tx);
9534 }
9535
9536 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9537         // In the first version of the chain::Confirm interface, after a refactor was made to not
9538         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9539         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9540         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9541         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9542         // spending transaction until height N+1 (or greater). This was due to the way
9543         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9544         // spending transaction at the height the input transaction was confirmed at, not whether we
9545         // should broadcast a spending transaction at the current height.
9546         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9547         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9548         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9549         // until we learned about an additional block.
9550         //
9551         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9552         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9553         let chanmon_cfgs = create_chanmon_cfgs(3);
9554         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9555         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9556         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9557         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9558
9559         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9560         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9561         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9562         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9563         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9564
9565         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9566         check_closed_broadcast!(nodes[1], true);
9567         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9568         check_added_monitors!(nodes[1], 1);
9569         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9570         assert_eq!(node_txn.len(), 1);
9571
9572         let conf_height = nodes[1].best_block_info().1;
9573         if !test_height_before_timelock {
9574                 connect_blocks(&nodes[1], 24 * 6);
9575         }
9576         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9577                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9578         if test_height_before_timelock {
9579                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9580                 // generate any events or broadcast any transactions
9581                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9582                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9583         } else {
9584                 // We should broadcast an HTLC transaction spending our funding transaction first
9585                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9586                 assert_eq!(spending_txn.len(), 2);
9587                 assert_eq!(spending_txn[0], node_txn[0]);
9588                 check_spends!(spending_txn[1], node_txn[0]);
9589                 // We should also generate a SpendableOutputs event with the to_self output (as its
9590                 // timelock is up).
9591                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9592                 assert_eq!(descriptor_spend_txn.len(), 1);
9593
9594                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9595                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9596                 // additional block built on top of the current chain.
9597                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9598                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9599                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: channel_id }]);
9600                 check_added_monitors!(nodes[1], 1);
9601
9602                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9603                 assert!(updates.update_add_htlcs.is_empty());
9604                 assert!(updates.update_fulfill_htlcs.is_empty());
9605                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9606                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9607                 assert!(updates.update_fee.is_none());
9608                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9609                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9610                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9611         }
9612 }
9613
9614 #[test]
9615 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9616         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9617         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9618 }
9619
9620 #[test]
9621 fn test_forwardable_regen() {
9622         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9623         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9624         // HTLCs.
9625         // We test it for both payment receipt and payment forwarding.
9626
9627         let chanmon_cfgs = create_chanmon_cfgs(3);
9628         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9629         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9630         let persister: test_utils::TestPersister;
9631         let new_chain_monitor: test_utils::TestChainMonitor;
9632         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9633         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9634         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9635         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9636
9637         // First send a payment to nodes[1]
9638         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9639         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9640         check_added_monitors!(nodes[0], 1);
9641
9642         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9643         assert_eq!(events.len(), 1);
9644         let payment_event = SendEvent::from_event(events.pop().unwrap());
9645         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9646         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9647
9648         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9649
9650         // Next send a payment which is forwarded by nodes[1]
9651         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9652         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9653         check_added_monitors!(nodes[0], 1);
9654
9655         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9656         assert_eq!(events.len(), 1);
9657         let payment_event = SendEvent::from_event(events.pop().unwrap());
9658         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9659         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9660
9661         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9662         // generated
9663         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9664
9665         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9666         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9667         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9668
9669         let nodes_1_serialized = nodes[1].node.encode();
9670         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9671         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9672         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9673         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9674
9675         persister = test_utils::TestPersister::new();
9676         let keys_manager = &chanmon_cfgs[1].keys_manager;
9677         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);
9678         nodes[1].chain_monitor = &new_chain_monitor;
9679
9680         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9681         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9682                 &mut chan_0_monitor_read, keys_manager).unwrap();
9683         assert!(chan_0_monitor_read.is_empty());
9684         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9685         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9686                 &mut chan_1_monitor_read, keys_manager).unwrap();
9687         assert!(chan_1_monitor_read.is_empty());
9688
9689         let mut nodes_1_read = &nodes_1_serialized[..];
9690         let (_, nodes_1_deserialized_tmp) = {
9691                 let mut channel_monitors = HashMap::new();
9692                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9693                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9694                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9695                         default_config: UserConfig::default(),
9696                         keys_manager,
9697                         fee_estimator: node_cfgs[1].fee_estimator,
9698                         chain_monitor: nodes[1].chain_monitor,
9699                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9700                         logger: nodes[1].logger,
9701                         channel_monitors,
9702                 }).unwrap()
9703         };
9704         nodes_1_deserialized = nodes_1_deserialized_tmp;
9705         assert!(nodes_1_read.is_empty());
9706
9707         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9708         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9709         nodes[1].node = &nodes_1_deserialized;
9710         check_added_monitors!(nodes[1], 2);
9711
9712         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9713         // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9714         // the commitment state.
9715         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9716
9717         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9718
9719         expect_pending_htlcs_forwardable!(nodes[1]);
9720         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9721         check_added_monitors!(nodes[1], 1);
9722
9723         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9724         assert_eq!(events.len(), 1);
9725         let payment_event = SendEvent::from_event(events.pop().unwrap());
9726         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9727         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9728         expect_pending_htlcs_forwardable!(nodes[2]);
9729         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9730
9731         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9732         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9733 }
9734
9735 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9736         let chanmon_cfgs = create_chanmon_cfgs(2);
9737         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9738         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9739         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9740
9741         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9742
9743         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9744                 .with_features(InvoiceFeatures::known());
9745         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9746
9747         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9748
9749         {
9750                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9751                 check_added_monitors!(nodes[0], 1);
9752                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9753                 assert_eq!(events.len(), 1);
9754                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9755                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9756                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9757         }
9758         expect_pending_htlcs_forwardable!(nodes[1]);
9759         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9760
9761         {
9762                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9763                 check_added_monitors!(nodes[0], 1);
9764                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9765                 assert_eq!(events.len(), 1);
9766                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9767                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9768                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9769                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9770                 // assume the second is a privacy attack (no longer particularly relevant
9771                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9772                 // the first HTLC delivered above.
9773         }
9774
9775         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9776         nodes[1].node.process_pending_htlc_forwards();
9777
9778         if test_for_second_fail_panic {
9779                 // Now we go fail back the first HTLC from the user end.
9780                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9781
9782                 let expected_destinations = vec![
9783                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9784                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9785                 ];
9786                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9787                 nodes[1].node.process_pending_htlc_forwards();
9788
9789                 check_added_monitors!(nodes[1], 1);
9790                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9791                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9792
9793                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9794                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9795                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9796
9797                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9798                 assert_eq!(failure_events.len(), 2);
9799                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9800                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9801         } else {
9802                 // Let the second HTLC fail and claim the first
9803                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9804                 nodes[1].node.process_pending_htlc_forwards();
9805
9806                 check_added_monitors!(nodes[1], 1);
9807                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9808                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9809                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9810
9811                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9812
9813                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9814         }
9815 }
9816
9817 #[test]
9818 fn test_dup_htlc_second_fail_panic() {
9819         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9820         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9821         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9822         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9823         do_test_dup_htlc_second_rejected(true);
9824 }
9825
9826 #[test]
9827 fn test_dup_htlc_second_rejected() {
9828         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9829         // simply reject the second HTLC but are still able to claim the first HTLC.
9830         do_test_dup_htlc_second_rejected(false);
9831 }
9832
9833 #[test]
9834 fn test_inconsistent_mpp_params() {
9835         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9836         // such HTLC and allow the second to stay.
9837         let chanmon_cfgs = create_chanmon_cfgs(4);
9838         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9839         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9840         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9841
9842         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9843         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9844         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9845         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9846
9847         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9848                 .with_features(InvoiceFeatures::known());
9849         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9850         assert_eq!(route.paths.len(), 2);
9851         route.paths.sort_by(|path_a, _| {
9852                 // Sort the path so that the path through nodes[1] comes first
9853                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9854                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9855         });
9856         let payment_params_opt = Some(payment_params);
9857
9858         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9859
9860         let cur_height = nodes[0].best_block_info().1;
9861         let payment_id = PaymentId([42; 32]);
9862         {
9863                 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();
9864                 check_added_monitors!(nodes[0], 1);
9865
9866                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9867                 assert_eq!(events.len(), 1);
9868                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9869         }
9870         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9871
9872         {
9873                 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();
9874                 check_added_monitors!(nodes[0], 1);
9875
9876                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9877                 assert_eq!(events.len(), 1);
9878                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9879
9880                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9881                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9882
9883                 expect_pending_htlcs_forwardable!(nodes[2]);
9884                 check_added_monitors!(nodes[2], 1);
9885
9886                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9887                 assert_eq!(events.len(), 1);
9888                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9889
9890                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9891                 check_added_monitors!(nodes[3], 0);
9892                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9893
9894                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9895                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9896                 // post-payment_secrets) and fail back the new HTLC.
9897         }
9898         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9899         nodes[3].node.process_pending_htlc_forwards();
9900         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9901         nodes[3].node.process_pending_htlc_forwards();
9902
9903         check_added_monitors!(nodes[3], 1);
9904
9905         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9906         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9907         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9908
9909         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }]);
9910         check_added_monitors!(nodes[2], 1);
9911
9912         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9913         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9914         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9915
9916         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9917
9918         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();
9919         check_added_monitors!(nodes[0], 1);
9920
9921         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9922         assert_eq!(events.len(), 1);
9923         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9924
9925         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9926 }
9927
9928 #[test]
9929 fn test_keysend_payments_to_public_node() {
9930         let chanmon_cfgs = create_chanmon_cfgs(2);
9931         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9932         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9933         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9934
9935         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9936         let network_graph = nodes[0].network_graph;
9937         let payer_pubkey = nodes[0].node.get_our_node_id();
9938         let payee_pubkey = nodes[1].node.get_our_node_id();
9939         let route_params = RouteParameters {
9940                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9941                 final_value_msat: 10000,
9942                 final_cltv_expiry_delta: 40,
9943         };
9944         let scorer = test_utils::TestScorer::with_penalty(0);
9945         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9946         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9947
9948         let test_preimage = PaymentPreimage([42; 32]);
9949         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9950         check_added_monitors!(nodes[0], 1);
9951         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9952         assert_eq!(events.len(), 1);
9953         let event = events.pop().unwrap();
9954         let path = vec![&nodes[1]];
9955         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9956         claim_payment(&nodes[0], &path, test_preimage);
9957 }
9958
9959 #[test]
9960 fn test_keysend_payments_to_private_node() {
9961         let chanmon_cfgs = create_chanmon_cfgs(2);
9962         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9963         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9964         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9965
9966         let payer_pubkey = nodes[0].node.get_our_node_id();
9967         let payee_pubkey = nodes[1].node.get_our_node_id();
9968         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9969         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9970
9971         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9972         let route_params = RouteParameters {
9973                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9974                 final_value_msat: 10000,
9975                 final_cltv_expiry_delta: 40,
9976         };
9977         let network_graph = nodes[0].network_graph;
9978         let first_hops = nodes[0].node.list_usable_channels();
9979         let scorer = test_utils::TestScorer::with_penalty(0);
9980         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9981         let route = find_route(
9982                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9983                 nodes[0].logger, &scorer, &random_seed_bytes
9984         ).unwrap();
9985
9986         let test_preimage = PaymentPreimage([42; 32]);
9987         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9988         check_added_monitors!(nodes[0], 1);
9989         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9990         assert_eq!(events.len(), 1);
9991         let event = events.pop().unwrap();
9992         let path = vec![&nodes[1]];
9993         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9994         claim_payment(&nodes[0], &path, test_preimage);
9995 }
9996
9997 #[test]
9998 fn test_double_partial_claim() {
9999         // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
10000         // time out, the sender resends only some of the MPP parts, then the user processes the
10001         // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
10002         // amount.
10003         let chanmon_cfgs = create_chanmon_cfgs(4);
10004         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10005         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10006         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10007
10008         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10009         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10010         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10011         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10012
10013         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10014         assert_eq!(route.paths.len(), 2);
10015         route.paths.sort_by(|path_a, _| {
10016                 // Sort the path so that the path through nodes[1] comes first
10017                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10018                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10019         });
10020
10021         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
10022         // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
10023         // amount of time to respond to.
10024
10025         // Connect some blocks to time out the payment
10026         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
10027         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
10028
10029         let failed_destinations = vec![
10030                 HTLCDestination::FailedPayment { payment_hash },
10031                 HTLCDestination::FailedPayment { payment_hash },
10032         ];
10033         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
10034
10035         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
10036
10037         // nodes[1] now retries one of the two paths...
10038         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10039         check_added_monitors!(nodes[0], 2);
10040
10041         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10042         assert_eq!(events.len(), 2);
10043         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10044
10045         // At this point nodes[3] has received one half of the payment, and the user goes to handle
10046         // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
10047         nodes[3].node.claim_funds(payment_preimage);
10048         check_added_monitors!(nodes[3], 0);
10049         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
10050 }
10051
10052 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10053         // Test what happens if a node receives an MPP payment, claims it, but crashes before
10054         // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10055         // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10056         // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10057         // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10058         // not have the preimage tied to the still-pending HTLC.
10059         //
10060         // To get to the correct state, on startup we should propagate the preimage to the
10061         // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10062         // receiving the preimage without a state update.
10063         //
10064         // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10065         // definitely claimed.
10066         let chanmon_cfgs = create_chanmon_cfgs(4);
10067         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10068         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10069
10070         let persister: test_utils::TestPersister;
10071         let new_chain_monitor: test_utils::TestChainMonitor;
10072         let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10073
10074         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10075
10076         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10077         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10078         let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10079         let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10080
10081         // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10082         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10083         assert_eq!(route.paths.len(), 2);
10084         route.paths.sort_by(|path_a, _| {
10085                 // Sort the path so that the path through nodes[1] comes first
10086                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10087                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10088         });
10089
10090         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10091         check_added_monitors!(nodes[0], 2);
10092
10093         // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10094         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10095         assert_eq!(send_events.len(), 2);
10096         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);
10097         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);
10098
10099         // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10100         // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10101         let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10102         if !persist_both_monitors {
10103                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10104                         if outpoint.to_channel_id() == chan_id_not_persisted {
10105                                 assert!(original_monitor.0.is_empty());
10106                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10107                         }
10108                 }
10109         }
10110
10111         let mut original_manager = test_utils::TestVecWriter(Vec::new());
10112         nodes[3].node.write(&mut original_manager).unwrap();
10113
10114         expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10115
10116         nodes[3].node.claim_funds(payment_preimage);
10117         check_added_monitors!(nodes[3], 2);
10118         expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10119
10120         // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10121         // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10122         // with the old ChannelManager.
10123         let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10124         for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10125                 if outpoint.to_channel_id() == chan_id_persisted {
10126                         assert!(updated_monitor.0.is_empty());
10127                         nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10128                 }
10129         }
10130         // If `persist_both_monitors` is set, get the second monitor here as well
10131         if persist_both_monitors {
10132                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10133                         if outpoint.to_channel_id() == chan_id_not_persisted {
10134                                 assert!(original_monitor.0.is_empty());
10135                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10136                         }
10137                 }
10138         }
10139
10140         // Now restart nodes[3].
10141         persister = test_utils::TestPersister::new();
10142         let keys_manager = &chanmon_cfgs[3].keys_manager;
10143         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);
10144         nodes[3].chain_monitor = &new_chain_monitor;
10145         let mut monitors = Vec::new();
10146         for mut monitor_data in [original_monitor, updated_monitor].iter() {
10147                 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10148                 monitors.push(deserialized_monitor);
10149         }
10150
10151         let config = UserConfig::default();
10152         nodes_3_deserialized = {
10153                 let mut channel_monitors = HashMap::new();
10154                 for monitor in monitors.iter_mut() {
10155                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10156                 }
10157                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10158                         default_config: config,
10159                         keys_manager,
10160                         fee_estimator: node_cfgs[3].fee_estimator,
10161                         chain_monitor: nodes[3].chain_monitor,
10162                         tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10163                         logger: nodes[3].logger,
10164                         channel_monitors,
10165                 }).unwrap().1
10166         };
10167         nodes[3].node = &nodes_3_deserialized;
10168
10169         for monitor in monitors {
10170                 // On startup the preimage should have been copied into the non-persisted monitor:
10171                 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10172                 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10173         }
10174         check_added_monitors!(nodes[3], 2);
10175
10176         nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10177         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10178
10179         // During deserialization, we should have closed one channel and broadcast its latest
10180         // commitment transaction. We should also still have the original PaymentReceived event we
10181         // never finished processing.
10182         let events = nodes[3].node.get_and_clear_pending_events();
10183         assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10184         if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10185         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10186         if persist_both_monitors {
10187                 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10188         }
10189
10190         // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10191         // ChannelManager prior to handling the original one.
10192         if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10193                 events[if persist_both_monitors { 3 } else { 2 }]
10194         {
10195                 assert_eq!(payment_hash, our_payment_hash);
10196         } else { panic!(); }
10197
10198         assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10199         if !persist_both_monitors {
10200                 // If one of the two channels is still live, reveal the payment preimage over it.
10201
10202                 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10203                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10204                 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10205                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10206
10207                 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10208                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10209                 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10210
10211                 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10212
10213                 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10214                 // claim should fly.
10215                 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10216                 check_added_monitors!(nodes[3], 1);
10217                 assert_eq!(ds_msgs.len(), 2);
10218                 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10219
10220                 let cs_updates = match ds_msgs[0] {
10221                         MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10222                                 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10223                                 check_added_monitors!(nodes[2], 1);
10224                                 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10225                                 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10226                                 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10227                                 cs_updates
10228                         }
10229                         _ => panic!(),
10230                 };
10231
10232                 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10233                 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10234                 expect_payment_sent!(nodes[0], payment_preimage);
10235         }
10236 }
10237
10238 #[test]
10239 fn test_partial_claim_before_restart() {
10240         do_test_partial_claim_before_restart(false);
10241         do_test_partial_claim_before_restart(true);
10242 }
10243
10244 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10245 #[derive(Clone, Copy, PartialEq)]
10246 enum ExposureEvent {
10247         /// Breach occurs at HTLC forwarding (see `send_htlc`)
10248         AtHTLCForward,
10249         /// Breach occurs at HTLC reception (see `update_add_htlc`)
10250         AtHTLCReception,
10251         /// Breach occurs at outbound update_fee (see `send_update_fee`)
10252         AtUpdateFeeOutbound,
10253 }
10254
10255 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10256         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10257         // policy.
10258         //
10259         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10260         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10261         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10262         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10263         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10264         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10265         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10266         // might be available again for HTLC processing once the dust bandwidth has cleared up.
10267
10268         let chanmon_cfgs = create_chanmon_cfgs(2);
10269         let mut config = test_default_channel_config();
10270         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10271         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10272         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10273         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10274
10275         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10276         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10277         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10278         open_channel.max_accepted_htlcs = 60;
10279         if on_holder_tx {
10280                 open_channel.dust_limit_satoshis = 546;
10281         }
10282         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10283         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10284         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10285
10286         let opt_anchors = false;
10287
10288         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10289
10290         if on_holder_tx {
10291                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10292                         chan.holder_dust_limit_satoshis = 546;
10293                 }
10294         }
10295
10296         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10297         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()));
10298         check_added_monitors!(nodes[1], 1);
10299
10300         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()));
10301         check_added_monitors!(nodes[0], 1);
10302
10303         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10304         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10305         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10306
10307         let dust_buffer_feerate = {
10308                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10309                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10310                 chan.get_dust_buffer_feerate(None) as u64
10311         };
10312         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;
10313         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10314
10315         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;
10316         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10317
10318         let dust_htlc_on_counterparty_tx: u64 = 25;
10319         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10320
10321         if on_holder_tx {
10322                 if dust_outbound_balance {
10323                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10324                         // Outbound dust balance: 4372 sats
10325                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10326                         for i in 0..dust_outbound_htlc_on_holder_tx {
10327                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10328                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10329                         }
10330                 } else {
10331                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10332                         // Inbound dust balance: 4372 sats
10333                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10334                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10335                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10336                         }
10337                 }
10338         } else {
10339                 if dust_outbound_balance {
10340                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10341                         // Outbound dust balance: 5000 sats
10342                         for i in 0..dust_htlc_on_counterparty_tx {
10343                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10344                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10345                         }
10346                 } else {
10347                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10348                         // Inbound dust balance: 5000 sats
10349                         for _ in 0..dust_htlc_on_counterparty_tx {
10350                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10351                         }
10352                 }
10353         }
10354
10355         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10356         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10357                 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 });
10358                 let mut config = UserConfig::default();
10359                 // With default dust exposure: 5000 sats
10360                 if on_holder_tx {
10361                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10362                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10363                         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)));
10364                 } else {
10365                         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)));
10366                 }
10367         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10368                 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 });
10369                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10370                 check_added_monitors!(nodes[1], 1);
10371                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10372                 assert_eq!(events.len(), 1);
10373                 let payment_event = SendEvent::from_event(events.remove(0));
10374                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10375                 // With default dust exposure: 5000 sats
10376                 if on_holder_tx {
10377                         // Outbound dust balance: 6399 sats
10378                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10379                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10380                         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);
10381                 } else {
10382                         // Outbound dust balance: 5200 sats
10383                         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);
10384                 }
10385         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10386                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10387                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10388                 {
10389                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10390                         *feerate_lock = *feerate_lock * 10;
10391                 }
10392                 nodes[0].node.timer_tick_occurred();
10393                 check_added_monitors!(nodes[0], 1);
10394                 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);
10395         }
10396
10397         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10398         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10399         added_monitors.clear();
10400 }
10401
10402 #[test]
10403 fn test_max_dust_htlc_exposure() {
10404         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10405         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10406         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10407         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10408         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10409         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10410         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10411         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10412         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10413         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10414         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10415         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10416 }
10417
10418 #[test]
10419 fn test_non_final_funding_tx() {
10420         let chanmon_cfgs = create_chanmon_cfgs(2);
10421         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10422         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10423         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10424
10425         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10426         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10427         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
10428         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10429         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
10430
10431         let best_height = nodes[0].node.best_block.read().unwrap().height();
10432
10433         let chan_id = *nodes[0].network_chan_count.borrow();
10434         let events = nodes[0].node.get_and_clear_pending_events();
10435         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: 0x1, witness: Witness::from_vec(vec!(vec!(1))) };
10436         assert_eq!(events.len(), 1);
10437         let mut tx = match events[0] {
10438                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10439                         // Timelock the transaction _beyond_ the best client height + 2.
10440                         Transaction { version: chan_id as i32, lock_time: best_height + 3, input: vec![input], output: vec![TxOut {
10441                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10442                         }]}
10443                 },
10444                 _ => panic!("Unexpected event"),
10445         };
10446         // Transaction should fail as it's evaluated as non-final for propagation.
10447         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10448                 Err(APIError::APIMisuseError { err }) => {
10449                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10450                 },
10451                 _ => panic!()
10452         }
10453
10454         // However, transaction should be accepted if it's in a +2 headroom from best block.
10455         tx.lock_time -= 1;
10456         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10457         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10458 }